Forum Moderators: open
I have a problem, which I can't solve.
I have a form in HTML. In this form there can be 1 or more checkboxes, depending on how many records are in the MySQL server.
These checkboxes have the same name but each checkbox has a different value. To pass these values to PHP, I need to add '[]' at the end of the name.
So far so good.
Before I let this send to the server and PHP, I want to do some data verification in Javascript. I want to check if one or more checkboxes are checked.
With the code I have so far, this works for 2 or more checkboxes. With 1 checkbox and this one is checked, I still get the alert "No order specified". It seems that an array with 1 value in it, is not recognized.
See the code:
function doSubmit(){
var form = document.forms[0];
var checkbox_choices=0;
for(i=0;i<form["order[]"].length;i++){
if(form["order[]"][i].checked){
checkbox_choices=checkbox_choices+1;
}
}
if(checkbox_choices==0) {
alert('No order specified!');
return false;
}
}
in the body:
<input type=checkbox name=order[] value=<php echo"$row[id]";?>>
What I'm doing wrong?
Either
1) Take that into account in the function.
or
2) Use document.getElementsByName("order[]")
- The W3C DOM collection methods always return a collection, even if it is length 1 or zero. This makes life easier for you here because the cases where you have only one box, or even no boxes at all, are automatically taken care of without error.
PS You don't need a counter (checkbox_choices) in your function. Just return true when you find a checked checkbox, and false at the end as a default.