Bala.C Bala.C - 1 year ago 156
Javascript Question

How to keep the serial number to stay with the sequence in a html table with dynamic add/remove?

I have a table like below and its rows can be added and removed by using the add/remove buttons.

<table class="dynatable">
<th><button class="add">Add</button></th>
<th>Col 3</th>
<th>Col 4</th>
<tr class="prototype">
<td><input type="text" name="id[]" value="0" class="id" /></td>
<td><input type="text" name="name[]" value="" /></td>
<td><input type="text" name="col4[]" value="" /></td>
<td><input type="text" name="col3[]" value="" /></td>

The first column in the table contains the serial number. But when the rows are removed in between it is losing its sequence.

For example if there are rows 5 rows with serial sequence of 1,2,3,4,5

If the row with the serial number of 3 is removed the serial number will lose the sequence to 1,2,4,5

But I want the serial numbers in the first column to keep the sequence like 1,2,3,4 after removing a row from a five rows

And if I add 5 rows and removed all the rows and start to add rows again. the sequence starts from 6 instead of 1.

How can I do it using jQuery?

Answer Source

I would recalculate the whole sequence when something is removed like this:

function recalcId(){
    $.each($("table tr.item"),function (i,el){
        $(this).find("td:first input").val(i + 1); // Simply couse the first "prototype" is not counted in the list

‚ÄčAlso when something is removed just to decresse the id

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download