romain
romain

Reputation: 26

javascript loop getElementById

I have a page containing a lots of text boxes with an incremental id. I'd like to read all these IDs and display them using javascript.

HTML page that looks like:

<input type="text" id="item1" value="111" ></input>
<input type="text" id="item2" value="222" ></input>
<input type="text" id="item3" value="333" ></input>

and a javascript part:

for (var i=1; i<3; i++){
    var values = parseInt(document.getElementById('item' + i).value);
    document.write(values);
}

I can't figure out why but only the first ID is displayed then firefox return an error (in the debugging console sysing: TypeError: document.getElementById(...) is null

Thanks for your help !

Romain

Upvotes: 0

Views: 2663

Answers (1)

Mike Vranckx
Mike Vranckx

Reputation: 5577

document.write is causing the problem, remove it outside the loop and it should work. Also, your for loop definition only loops for 2 elements, not the 3th one ...

var values = [], i = 0;
for (; i < 4; i += 1) {
    values.push(parseInt(document.getElementById('item' + i).value, 10));
}

document.write(values.join(', '));

Upvotes: 5

Related Questions