0

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

7
  • 1
    When "the first ID is displayed", what does the page look like? Is it a white screen with just "111" in the upper left corner? Commented Dec 15, 2013 at 20:26
  • On JSFiddle looks OK: jsfiddle.net/xFZz8 Commented Dec 15, 2013 at 20:27
  • 4
    BTW: for(var i=1; i<3; i++) will write only 2 elements Commented Dec 15, 2013 at 20:27
  • 5
    @romain the likely problem is that document.write() obliterates the entire page when it's called after the page has completed. Commented Dec 15, 2013 at 20:27
  • 1
    When document.write() is used on a document that is already loaded, it clears the current document and starts a new blank one, thus wiping out your current DOM. Chance are you don't want to use document.write() here at all. Commented Dec 15, 2013 at 20:57

1 Answer 1

5

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(', '));
Sign up to request clarification or add additional context in comments.

1 Comment

wouldn't it be : var values = [], i; for (i=0; i < 4; ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.