1

I am creating a simple function that increment number and bind with multiple Table as S.NO.. I don't understand what's wrong with my code.

    function _IncrementNumber(id) {
        var table = document.getElementById(id);
        var rowCount = table.rows.length;
        for (var i = 0; i < rowCount; i++) {
            table.rows[i + 1].cells[0].innerHTML = (i + 1);
        }
    }
$(document).ready(function () {
    _IncrementNumber("FirstTable");
    _IncrementNumber("SecondTable");
});

DEMO Please guide me.

1
  • 1
    you start with table.rows[1], thus skipping table.rows[0] Commented Oct 14, 2014 at 9:44

3 Answers 3

3

You are accessing i+1 instead of i.
In the last iteration -> you will go out of bounds.

function _IncrementNumber(id) {
        var table = document.getElementById(id);
        var rowCount = table.rows.length;
        for (var i = 0; i < rowCount; i++) {
            table.rows[i].cells[0].innerHTML = (i + 1);
        }
}
$(document).ready(function () {
    _IncrementNumber("FirstTable");
    _IncrementNumber("SecondTable");
});
Sign up to request clarification or add additional context in comments.

1 Comment

i start incremented value after table heading so i think i have to use rowCount-1 and rows[i+1]
0

You're trying to access a row that doesnt exist.

You should start with i=1 instead to skip the header row

for (var i = 1; i < rowCount; i++) {
    table.rows[i].cells[0].innerHTML = (i);
}

Comments

0

the error at this line was the issue. Table rows starts from 0 index. so dont need to increment the rows index change to this table.rows[i].cells[0].innerHTML = (i + 1);

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.