2

I have created a form where you can add or delete table rows using javascript and jQuery. I would like to know how I can obtain and set the index for each table row such that sequence is maintained even if I were to delete and element from the middle of the table. The table is of the form:

<thead>
    <tr>
        <th>Index</th>
        <th>Name</th>
        <th>Property</th>
        <th>Edit/Delete</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td class="index">Index goes here (1)</td>
        <td>NameOne</td>
        <td>PropOne</td>
        <td><span class="edit">Edit Icon</span> <span class="delete">Delete Icon</span></td>
    </tr>
    <tr>
        <td class="index">2</td>
        <td>NameTwo</td>
        <td>PropTwo</td>
        <td><span class="edit">Edit Icon</span> <span class="delete">Delete Icon</span></td>
    </tr>
    <tr>
        <td class="index">3</td>
        <td>NameThree</td>
        <td>PropThree</td>
        <td><span class="edit">Edit Icon</span> <span class="delete">Delete Icon</span></td>
    </tr>
</tbody>

Now what I want to achieve is if I were to delete the second row, the index of the previous third row should automatically change to 2 and if I were to add new element it should automatically take the index value of 3 and so on.

I tried to achieve this with:

function setIndex(){
   $("td.index").each(function(index) {
       $(this).text(++index);
   });
}

But when I used the above function although the initial index when the elements were added printed properly the index wouldn’t update properly when I called the function again after deleting or editing a row( I deleted the row using jQuery remove).

Also I am creating the new table rows with jQuery append().

I think that although I used remove() they don’t get deleted completely as when I used a console.log(“test”) statement inside the setIndex() although “test” was only supposed to be printed twice(I had initially created 3 rows and deleted one of them) it go printed thrice signifying that there were 3 tr.index’s.

Please help me solve the same.