0

I have a html button that calls this function. But for unknown reason it only goes 3 iterations.

Can anyone help or refer me to some good example why the for loop breaks after the third iteration?

for(i = 1; i < 10; i++) {
   alert(i);
  if (document.getElementById(i).checked) {
    alert("dda3");
    act = act + document.getElementById("TD" + i).innerHTML + delimiter;
  }
}
3
  • 2
    can you put your html code part? Commented Dec 1, 2012 at 10:35
  • Have you tried looking at the javascript console? Commented Dec 1, 2012 at 10:36
  • 1
    Seems to work fine - jsFiddle. Commented Dec 1, 2012 at 10:38

2 Answers 2

2

The most likely reason is that you don't have an element with the id value "4". Consequently, document.getElementById returns null, and then when you try to look at the checked attribute, you're dereferencing a null, which throws an exception. Or of course, you don't have an element with the id value "TD4" and so your later getElementById returns null and you get the exception when assigning to innerHTML.

When trying to debug things, it's best to use a debugger. All modern browsers have debuggers built in — and some of them are quite good. On most browsers, pressing F12 will bring up the debugger, but if not go looking through the menus for "developer tools" or similar.

Even if there's no debugger, all browsers going back more than a decade have a means of telling you about JavaScript errors. I would at the very least enable that so you can see errors.


Side note: id values starting with digits are only recently allowed in HTML (valid in HTML5, not valid in HTML4 or earlier) and are still not valid in CSS. I recommend avoiding them.

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

Comments

0

Probably you dont have an element with that ID and thats why it breaks the for loop , go try in the html part of your code where you initialize the names of the where you don't increment or decrement if you do it correctly ( in while of for or foreach loop) maybe you are using the same $i variable for 2 different loops or changing its value (other than $i++ or $i--)

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.