javascript - How to reorder the table serial no after deleting the row

26

I have a table with few buttons in each row. I have to remove the table row when I click the delete button of each row. My problem here is when I delete the row the S.N. is not arranged in order. For Example: if there are 5 rows and once I remove the first row, it will order as 2, 3, 4, 5 instead of 1, 2, 3, 4.

<table>
<thead>
    <tr>
        <th>S.N.</th>
        <th>Name</th>
        <th>Address</th>
        <th>Modified Date</th>
        <th>Action</th>
    </tr>
</thead>
<tbody>
    <?php 
    $sn = 1;
    while($result= mysql_fetch_row($res))
    {

        ?>
        <tr id=<?= $result[0];?>>
            <td><? echo $sn++; ?></td>
            <td><? echo $result[1] ?></td>
            <td><? echo $result[2] ?></td>
            <td><? echo $result[3] ?></td>
            <td>
                <a href="#" id="delete">Delete</a>
                <a href="#" id="edit">Edit</a>
            </td>

        </tr>

        <?php } ?>
    </tbody>
</table>

$('#delete').on('click', function(e) {
    e.preventDefault();
    var id = $(this).closest('tr').attr('id');
    $(this).closest('tr').remove();
});
32

Answer

Solution:

First of all you should not have same ID. IDs must be unique. you can rather use class and then class selector to target those elements:

$('.delete').on('click......

For reordering, you can use index of element in.attr callback function to set id based on index:

$('table tbody tr').attr('id',function(i,o){
  return i++ ;
});

People are also looking for solutions to the problem: php - Paypal: How to display payer's email on the thank you page?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.