Reputation: 8648
I used normal addRow function and removeRow function to dynamically add and remove the row in a table.
function addRow()
{
var ptable = document.getElementById('ptableQuestion');
var lastElement = ptable.rows.length;
var index = lastElement;
var row = ptable.insertRow(lastElement);
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(index);
cellLeft.appendChild(textNode);
var cellText = row.insertCell(1);
var element = document.createElement('textarea');
element.name = 'question' + index;
element.id = 'question' + index;
element.rows="2";
element.cols="60"
var cellText1 = row.insertCell(2);
var element1 = document.createElement('input');
element1.type = 'checkbox';
element1.name = 'cb';
element1.id = 'cb';
cellText.appendChild(element);
cellText1.appendChild(element1);
document.getElementById("psize").value=index;
}
function checkCheckboxes() {
var e = document.getElementsByName("cb");
var message = 'Are you sure you want to delete?';
var row_list = {length: 0};
for (var i = 0; i < e.length; i++) {
var c_box = e[i];
if (c_box.checked == true) {
row_list.length++;
row_list[i] = {};
row_list[i].row = c_box.parentNode.parentNode;
row_list[i].tb = row_list[i].row.parentNode;
}
}
if (row_list.length > 0 && window.confirm(message)) {
for (i in row_list) {
if (i == 'length') {
continue;
}
var r = row_list[i];
r.tb.removeChild(r.row);
}
} else if (row_list.length == 0) {
alert('You must select an email address to delete');
}
}
<form action="show.jsp" method="post" onsubmit="return validate();">
<input type="hidden" name="psize" id="psize">
<table style="border:1px solid #000000;" bgcolor="#efefef"
id="ptablePerson" align="center">
<tr>
<th colspan="3">Add New Person</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" name="person1" id="person1" size="30" />
<input type="button" value="Add" onclick="addRow();" /></td>
<td><input type="checkbox" id="cb" name="cb"/></td>
</tr>
</table>
<table align="center">
<tr>
<td><input type="button" value="Remove" onclick="checkCheckboxes();" />
<input type="Submit" value="Submit" /></td>
</tr>
</table>
</form>
</BODY>
</HTML>
My problem is when the table got 5 row, if i click checkbox to delete row 3 the index become 1 2 4 5. Is there any method can rearrange it to 1 2 3 4
Upvotes: 3
Views: 2806
Reputation: 15630
There is a small code i which i has created a spn in every td.So that I will replace the value in the iterartion. It will work if u deleted 3(1,2,3,4,5) then the content of span will be 1,2,3,4 .Jquery i am using here
var rowCount = $('#ptableQuestion tr').length;
if (rowCount != 0) {
i = 0;
$('#ptableQuestion tr').each(function(i) {
$(this).find("td .spn").html(i);
});
}
});
Hope it will work for you.
Upvotes: 1
Reputation: 6004
This looks like simple delete element from the list. You have to get all the rows of the table, and shift all rows one step backword after delete operation is completed.
Upvotes: 1