0

I want to update the index when the Rows are deleted in the Table. For e.g. I delete row 1, then the rows 2 and 3 should become 1 and 2, so on.

function deleteRow(tableID) {
            try {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;

            for(var i=0; i<rowCount; i++) {
                var row = table.rows[i];
                var chkbox = row.cells[0].childNodes[0];
                if(null != chkbox && true == chkbox.checked) {
                    table.deleteRow(i);
                    rowCount--;
                    i--;
                }


            }
            }catch(e) {
                alert(e);
            }
        }
1
  • Can you please post an example of what the HTML for the table would look like? Commented Aug 30, 2012 at 6:42

2 Answers 2

2

Well you dont need to do anything! when ever a row is deleted from dom, automatically the row index is changed.

if you want to closely examine you can hook an mutationevent DOMNodeRemoved and see whats happening, or just keep a break point after delete and verify the row count and indexes.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is a complete jQuery solution:

Test it here. Just click on a row to delete it.

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js""></script>

    <script>
        $(function () {

            $('tr').click(function () {

                $(this).remove()
                recountRows();
            });


            var recountRows = function () {
                var index = 1;

                $('.index').each(function () {
                    $(this).html(index);
                    index++;
                });
            }


        });
    </script>
</head>
<body>
    <table>
        <tr>
            <td class="index">1</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">2</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">3</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">4</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">5</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">6</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">7</td><td>table text</td>
        </tr>
        <tr>
            <td class="index">8</td><td>table text</td>
        </tr>


    </table>


</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.