Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
196
rated 0 times [  199] [ 3]  / answers: 1 / hits: 37594  / 12 Years ago, thu, august 30, 2012, 12:00:00

I want to add/remove rows in a table dynamically. I have javascript function to add and remove the rows. But, I want the delete button beside every single row so that I can delete a particular row.



ANd I want to add a row only if the first row is completely filled.



function to remove row



 function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}


function to add rows:



function addRow(tableID) {

var table = document.getElementById(tableID);

var rowCount = table.rows.length;
var row = table.insertRow(rowCount);

var cell1 = row.insertCell(0);
var element1 = document.createElement(input);
element1.type = text;
cell1.appendChild(element1);

var cell2 = row.insertCell(1);
var element2 = document.createElement(input);
element2.type = text;
cell2.appendChild(element2);
}


my table:



<table id=tableId>
<tr><td>Host Name</td><td>Directory</td></tr>
<tr><td><input type=text/></td><td><input type=text/></td></tr>
<tr><td><input type=button value=+ onclick=addRow(tableId)/></td>
<td><input type=button value=- onclick=removeRowFromTable()/></td></tr>
</table>


Any help is appreciated! Thanks in Advance!!!


More From » html

 Answers
24

If you put a delete button on each row, then:



<tr>
<td><input type=button value=Delete row onclick=deleteRow(this)>
<td><input type=text>
<td><input type=text>
</tr>


And the deleteRow function can be:



function deleteRow(el) {

// while there are parents, keep going until reach TR
while (el.parentNode && el.tagName.toLowerCase() != 'tr') {
el = el.parentNode;
}

// If el has a parentNode it must be a TR, so delete it
// Don't delte if only 3 rows left in table
if (el.parentNode && el.parentNode.rows.length > 3) {
el.parentNode.removeChild(el);
}
}


BTW, if all your rows have the same content, it will be much faster to add a row by cloning an existing row:



function addRow(tableID) {
var table = document.getElementById(tableID);

if (!table) return;

var newRow = table.rows[1].cloneNode(true);

// Now get the inputs and modify their names
var inputs = newRow.getElementsByTagName('input');

for (var i=0, iLen=inputs.length; i<iLen; i++) {
// Update inputs[i]
}

// Add the new row to the tBody (required for IE)
var tBody = table.tBodies[0];
tBody.insertBefore(newRow, tBody.lastChild);
}

[#83320] Wednesday, August 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristineterrak

Total Points: 74
Total Questions: 109
Total Answers: 115

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;