I have this validate form function:
function ValidateForm() {
var chks = document.register.elements['sendto[]'];
var hasChecked = false;
for (var i=0;i<chks.length;i++){
if (chks[i].checked){
hasChecked = true;
break;
}
}
if (!hasChecked){
alert("Please select at least one friend.");
chks[0].focus();
return false;
}
}
html for this is:
<input type="checkbox" name="sendto[]" value="2" >
I know this is not full code. Full code is huge. But basically if i have only one checkbox in the code the above code gives a message undefined on ValidateForm(). Which is called when form is submitted and and above checkbox is checked.
But if i have two checkboxes in the code like this:
<input type="checkbox" name="sendto[]" value="2" >
<input type="checkbox" name="sendto[]" value="4" >
On submit when ValidateForm() function is called this works correctly. Am i doing something wrong that it is not working for 1 checkbox even if it is checked?
The statement
gets the element (element*s*, if there are more then one) with name
sendto[]If there is only one element with name
sendto[]then you have the reference of that element inchks.If there are more than one element with name
sendto[], thenchksholds the reference to the array of those elements.When you do this:
You try to loop based on
chks.length. Ifchksis an array (see above: when there are multiple elements by namesendto[]), thenchks.lengthwill hold the number of elements in the array.If there is only one
sendto[]element, then chks will hold that element and since the element (<input type="checkbox" name="sendto[]" value="2" >) does not have a property calledlength, the browser says length is indefinedSo you have o differentiate between two scenarios, when there is only one
sendto[]checkbox and when there are more than one.:PS:
code gives a message undefined on ValidateForm() does not convey much. Even for you it is not clear what this means right (That’s why you have asked this question). Try to give more details. Any modern browser will give more details on the undefined, the what is undefined which line etc. Even pre-historic browsers will tell you the line number where the undefined error was thrown. With those details you can try to find the line and try to see what is happening. You most likely will find out. If you don’t, post it to the community here with all these details.