Delete and reset html table row ids for the rest of the table
how to reset html table row id and name after row deletion using jquery. For example the html table has 5 rows and if I delete the 3rd row then the actual 4th and 5th rows of the textbox should become 3 and 4
<script type="text/javascript">
$("#add").on("click",function() {
var data ='<tr><td>2</td><td><input type="text" id="name2" value=""/></td><td><input type="text" id="phone2" value=""/></td><td><input type="text" id="email2" value=""/></td><td><button id="delete">Delete</button></td></tr>';
$("tbody").append(data);
});
</script>
<button id="add">Add Row</button>
<table>
<tbody>
<tr>
<td>1</td>
<td><input type="text" id="name1" value=""/></td>
<td><input type="text" id="phone1" value=""/></td>
<td><input type="text" id="email1" value=""/></td>
<td><button id="delete">Delete</button></td>
</tr>
</tbody>
</table>
source to share
So, first you have to declare a global counter for window.globalCounter = 2;
where you will store the row count. (what index will the added row have)
Then when you add the increment, <<21>.
And when you delete, you have to select currentRow, decrement the counter and reorganize the indexes.
$("tbody").on("click", "#delete", function (ev) {
// delete row
var $currentTableRow = $(ev.currentTarget).parents('tr')[0];
$currentTableRow.remove();
window.globalCounter--;
// refactor indexes
$('table').find('tr').each(function (index) {
var firstTDDomEl = $(this).find('td')[0];
var $firstTDJQObject = $(firstTDDomEl);
$firstTDJQObject.text(index + 1);
});
});
Here's a snippet of working code.
window.globalCounter = 2;
$(document).ready(function () {
$("#add").on("click", function () {
var data = '<tr><td>' + window.globalCounter + '</td><td><input type="text" id="name2" value=""/></td><td><input type="text" id="phone2" value=""/></td><td><input type="text" id="email2" value=""/></td><td><button id="delete">Delete</button></td></tr>';
$("tbody").append(data);
window.globalCounter++;
});
$("tbody").on("click", "#delete", function (ev) {
var $currentTableRow = $(ev.currentTarget).parents('tr')[0];
$currentTableRow.remove();
window.globalCounter--;
$('table').find('tr').each(function (index) {
var firstTDDomEl = $(this).find('td')[0];
var $firstTDJQObject = $(firstTDDomEl);
$firstTDJQObject.text(index + 1);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="add">Add Row</button>
<table>
<tbody>
<tr>
<td>1</td>
<td>
<input type="text" id="name1" value="" />
</td>
<td>
<input type="text" id="phone1" value="" />
</td>
<td>
<input type="text" id="email1" value="" />
</td>
<td>
<button id="delete">Delete</button>
</td>
</tr>
</tbody>
</table>
You have an alternative working jsfiddle here: https://jsfiddle.net/cn5p4oke/
Of course, you have to configure the parameters of phone2, email2, name2.
Please note that I was using jQuery 2.1.0.
source to share