Remove dynamically appended <TR> from jquery - javascript

I append the <tr> to <tbody>
for (var i = 0 ;i < 12 ;i++){
$(`<tr><td>test</td></tr>`).appendTo('#songsTbody');
}
to this html.
<tbody id="songsTbody">
</tbody>
Now I want to remove() only appended <tr> but
$('#songsTbody').remove();
it remove <tbody> itself.
How can I remove only <tr>??

You can pass a selector into the .remove() call so if there are no other s and you want to remove them all, you could do $('#songsTbody').remove('tr') or even just $('#songsTbody tr').remove().
If you need to just remove the last one that was added, you could try $('#songsTbody tr:last-child').remove() or $('#songsTbody').remove('tr:last-child')

You can recognize appended <TR> adding a data attribute or a class.
for (var i = 0 ;i < 12 ;i++){
$(`<tr class="appended"><td>test</td></tr>`).appendTo('#songsTbody');
}
and after you can easily remove just new TR with
$('#songsTbody').remove('tr.appended')

Save it in a variable(s).
var arr = []
for (var i = 0; i < 12; i++) {
var elem = $(`<tr><td>test</td></tr>`);
elem.appendTo('#songsTbody');
arr.push(elem);
}
// remove:
arr.forEach((elem) => elem.remove());

Related

JS create new child TR with two TD bits of information

I have the following problem - I am having difficulty creating the new TR row dynamically and then getting it to insert the data as a new table (TD) line.
The full question is as below;
Create a script that inserts a new row with the values March and £580 as the last child of the following HTML table.
<table id=”takings”>
<tr>
<td>January</td>
<td>£100</td>
</tr>
<tr>
<td>February</td>
<td>£300</td>
</tr>
// insert here
</table>
My attempt or idea was to create the TR first and then for each item in the text array add a TD within that newly created TR. However this doesn't seem to create anything.
My JS is as below;
function insertNode(newNodeTypeTD, newNodeTypeTR, newNodeTextArray, element) {
let parentElement = document.getElementById(element);
let newTR = document.createElement(newNodeTypeTR);
for (let i = 0; newNodeTextArray.length; i++) {
let newText = document.createTextNode(newNodeTextArray);
newTR.appendChild(newText);
parentElement.insertBefore(newTR, parentElement.children[i]);
}
}
window.onload = function() {
insertNode("td", "tr", ["March", "£580"], "takings")
}
Note this line: for (let i = 0; newNodeTextArray.length; i++) {
newNodeTextArray.length is 1 or greater, so this condition always returns true.
What you likely meant to do was
for (let i = 0; i < newNodeTextArray.length; i++) {

How to find the last table cell which doesn't have text value and put a message?

I want to detect the last table row cell of a table which doesn't have any value (text).
var all_product_cell = document.getElementsByClassName("product-cell");
for (var i = 0; i < all_product_cell.length; i++) {
var td = all_product_cell[i];
alert(all_product_cell.length);
}
This code returns the table rows length... but I don't know how to check the last row which is clean and put there a message "hello!"...
UPDATE :
With this code system find last cell and put HELLO, but how I check the last cells who haven't text value and put the Hello there?
var all_local_cell = document.getElementsByClassName("product-cell");
for (var i = 0; i < all_local_cell.length; i++) {
var td = all_local_cell[i];
total_rows = all_local_cell.length-1;
all_product_cell[total_rows].value = "HELLO";
const productTable = document.querySelector(".your-product-table"); // get the table
const textOnLastCell = productTable
.rows[productTable.rows.lenght -1] // get last row
.cells[productTable.rows[productTable.rows.lenght -1].cells.lenght -1] // get last cell of last row
.innerText // get inner text
You can get last row of table by using below line :
var product_table = document.getElementsByClassName("product-cell");
console.log(product_table);
for (var i = 0; i < product_table.length; i++) {
total_rows = product_table[i].rows.length;
last_row = product_table[i].rows[total_rows-1];
last_row_length = last_row.cells.length;
last_column = last_row.cells[last_row_length-1]; // directly get last cell
If(last_column.innerHTML() == “”){
last_column.innerHTML = “Hello friend”;
}
console.log(last_column.innerHTML);
for(var j =0;j<last_row.cells.length;j++){ // you can find through loop using which cells is empty
console.log(last_row.cells[j]);
}
// console.log(last_row);
}
If you give html code will help better way.
https://codepen.io/aviboy2006/pen/ZEYBWWE
Here's a table with two empty TD'S.
The function will get an array of all TD's with the class product-cell and loop through each cell and check if innerHTML is empty, and then it will set lastTD to the last empty TD and set its innerHTML to "Hallo"
setTextLastEmptyCell()
function setTextLastEmptyCell(){
let tds = document.getElementsByClassName('product-cell')
for(let td of tds){
if(td.innerHTML === '') lastTD = td
}
lastTD.innerHTML = 'HALLO'
}
<table>
<tr>
<td class="product-cell">ABC</td>
<td class="product-cell">DEF</td>
<td class="product-cell">CBA</td>
</tr>
<tr>
<td class="product-cell"></td>
<td class="product-cell">CDA</td>
<td class="product-cell">ACB</td>
</tr>
<tr>
<td class="product-cell">ABC</td>
<td class="product-cell"></td>
<td class="product-cell">DEF</td>
</tr>
</table>

Repeat script for multiple elements

Hey i have this code:
<body>
<table>
<tr>
<td class="first">100</td>
</tr>
</table>
<h4 class=curs style="display:none">10</h4>
<script>
document.body.onload = function(){
var firstTdVal = document.getElementsByClassName('first')[0].innerHTML;
var secondTdVal = document.getElementsByClassName('curs')[0].innerHTML;
var valueToBeShown = parseInt(firstTdVal)/ parseInt(secondTdVal);
document.getElementsByClassName('first')[0].innerHTML = valueToBeShown ;
}
</script>
</body>
As you see ".first" has a number in it,this number is divied to ".curs" and the result is showed in ".first" too.Now the problem is that for exemple i add 100 more td's with class ".second,.third...,.hundred" in table.How to make script to do the same for all td's as it does for the ".first"(devide to ".curs").How do i do this in my JS by keeping it complex.
Use document.querySelectorAll to get an array of matched elements (matched with CSS selector), then loop through them using forEach, applying you logic one td at a time. Like this:
// querySelector gets the first element matched. textContent get the text of that element
var cursValue = parseInt(document.querySelector(".curs").textContent);
// querySelectorAll get an array of all the matched elements
var tds = document.querySelectorAll("td");
// loop through that array one td at a time
tds.forEach(function(td){
// get the text of the current td
var value = parseInt(td.textContent);
// if the value is not valid (a string for example) return and don't process anymore for this td (go straight to the next one).
if(isNaN(value)) return;
// calculate the new value
value = value / cursValue;
// change the text of this td (update it to the new value)
td.textContent = value;
});
NOTE: querySelector and querySelectorAll match elements using CSS selectors, so to match an element using a class the selector should be ".className", to match it using an ID: "#someID", ... All CSS selectors are accepted (even this one: "#anID>li.some-class a:not([href])").
NOTE2: tds is an array, so if you don't want to use forEach you can use a normal for loop (for(var i = 0; i < tds.length; i++) ...).
This will iterate over your table (be sure to set the table ID) (open dev console to view output but it's pretty straight forward.)
var table = document.getElementById("myTable");
for (var row of table.rows) {
for (var col of row.cells) {
console.log(col.className, col.innerHTML); //Class names and the values of the elements.
}
}
If you need anymore help please ask because I do not fully understand what you're trying to do here.
Here's a way where you put the number to be divided by in the first td, the number to divide by in the second td, and the result will be placed in the third td.
var trs = document.getElementsByTagName('tr');
for (var i = 0; i< trs.length; i++) {
var tds = trs[i].getElementsByTagName('td'),
first = tds[0].textContent,
second = tds[1].textContent,
third = tds[2],
result = (parseInt(first) / parseInt(second));
third.innerHTML = result;
}
<table>
<tr>
<td>10</td>
<td>2</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td></td>
</tr>
</table>

Dynamically delete multiple columns in html table

I am trying to delete multiple columns from html table using javascript.
The logic it is using is that it searches in top row for tag "" and then deletes that column.
The problem is if only one cell in top row is having '', then it deletes that columns fine, but if there are multiple columns it throws error.
Here is my code
<!DOCTYPE html>
<html>
<body>
<table style="width:100%" border='1' id='Just_for_california'>
<tr>
<td><span></span></td>
<td>S</td>
<td><span></span></td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body>
<script>
var dataTable_length = document.getElementById('Just_for_california').rows[0].cells.length;
var count_rows = document.getElementById('Just_for_california').rows.length;
var column_array = [];
for(var i=0; i<dataTable_length; i++)
{
var str = document.getElementById("Just_for_california").rows[0].cells[i].innerHTML;
if(str.search("<span></span>") != -1)
{
column_array.push(i);
}
}
var len = column_array.length;
for(var i=count_rows-1 ; i>=0;i--)
{
rows_number = document.getElementById('Just_for_california').rows[i];
console.log("row_number:"+i);
for(var j=0; j<len;j++)
{
rows_number.deleteCell(column_array[j]);
}
}
</script>
</html>
It happens because you calculate indexes incorrectly when you delete cells. I refactored you code (making it clearer) and it seems to work now:
var table = document.getElementById('Just_for_california'),
rows = table.rows;
for (var i = 0; i < rows[0].cells.length; i++) {
var str = rows[0].cells[i].innerHTML;
if (str.search("<span></span>") != -1) {
for (var j = 0; j < rows.length; j++) {
rows[j].deleteCell(i);
}
}
}
The problem is that you are trying to remove cells "horizontally" in the row. So say you want to delete cells at indexes 1 and 3 and there are 4 columns in the table. When you delete the first cell 1 it works fine. However then you move to the right and try to remove cell at index 3. This fails because since you have already removed cell 1, there is no cell with index 3 anymore. The maximum index now is 2. Hence the error.
In my improved code I'm removing columns "vertically", so such an issue can't happen.
Demo: http://jsfiddle.net/t2q60aag/

getting tr index in a table

I have the below table and I am using the below code to get the index of the tr with the id tbl1.The issue is that the index being returned which should be 2 is coming out correct in IE but it is coming as 3 in chrome and firefox.Can someone please tell me what I am doing wrong here.
var parent = document.getElementById("tbl1").parentElement;
var tr = document.getElementById("tbl1");
var index = -1;
for (var i = 0; i < parent.childNodes.length; i++) {
if (parent.childNodes.item(i) == tr) {
index = ++i;
break;
}
}
<TABLE border=0 cellSpacing=0 cellPadding=0><TBODY>
<TR>
</TR>
<TR id="tbl1">
</TR>
<TR></TR>
</TBODY></TABLE>
How about just use rowIndex:
var tr = document.getElementById("tbl1"),
index = tr.rowIndex + 1;
console.log(index); // => 2
See demo
I know you didn't ask for a solution using jQuery, anyway:
$('#tbl1').index()+1
gives you 2 as well.
It works for any kind of node, not only TR.

Categories

Resources