Sorry I know this place is mainly for C. But I don't really want to have to register to another site for this JS question. (I'm sure a lot of you have dealt with websites anyway )
This question is pretty simple, but I just can't figure out why the FOR loop breaks. To me it seems like a bug. It simply breaks after 1 iteration.
I created a dummie page, for you to see. Simply save it as a .html and run it
Code:
<html><head><script type="text/javascript">
function validateForm()
{
var fields = new Array;
var fields =[
document.getElementById("one"),
document.getElementById("two"),
document.getElementById("three")];
for (var i = 0; i < parseInt(fields.length); i++) {
alert(i);
if ( fields[i].value == "" ) {
alert("Field" + (i+1) + " has no value");
}
}
}
</script></head><body>
<form name="form1">
Field 1 enter: <input type="text" id="one"> <br />
Field 2 enter: <input type="text" name="two"> <br />
Field 3 etner: <input type="text" name="three"> <br /><br />
<input type="button" onclick="validateForm()" value="Submit" />
</form></body></html>
The error occurs on fields[i].value .. The error is the var i
You see, if you replace i with 0: fields[0].value, it will successfully loop 3 times.
I just don't understand why using that variable, fails?
I tried so many things, moving the script to bottom of page, converting value of i to a char, etc. I may of missed something, but if you take a quick look maybe you know this problem. (I know I can resort to doing multiple IF statement, I just want to know why this logical loop doesn't work)