ANJYR
ANJYR

Reputation: 2623

My Javascript code not working properly

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.

Upvotes: 2

Views: 123

Answers (3)

Khaleel
Khaleel

Reputation: 1371

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);

Upvotes: 0

smokiespartakus
smokiespartakus

Reputation: 176

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);
}

Upvotes: 0

Amir Popovich
Amir Popovich

Reputation: 29836

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");
});

Upvotes: 3

Related Questions