Have you ever had to collect a series of values from check boxes, or any other input for that matter and put them in $_POST arrays to save precious precious lines? Ala:
Great right? Because when the form is executed all values of “this_one” that were checked are conveniently stored in the array:
$_POST['this_one']
But… wait a sec… what if you have some validation going on with this form and you have to use a client side script such as JavaScript to check whether or not those boxes are checked.
With the above HTML, you can’t use:
var chks = document.form_name.this_one;
OR
var chks = document.form_name.this_one[];
So what’s a young man or woman to do?
Dry those tears buttercup, the answer is simpler than you think! Just change the way you’re accessing your checkboxes (or input elements). This way you can use your fancy PHP Array AND do your JavaScript validation, ala:
The Fix:
var chks = document.getElementsByName('this_one[]');
Now you can run a JavaScript loop:
var chks = document.getElementsByName('this_one[]');
var the_checked = false;
for (var i = 0; i < chks.length; i++) {
if (chks[i].checked) {
the_checked = true;
break;
}
}
if (the_checked == true) {
alert('Cannot Proceed! At least one box is Checked!');
return false;
}
AND still get your nice PHP Array:
print_r($_POST['this_one']);
And it validates! The world... the sun moon and stars... they be happy now.
thank you so much, had the same problem! btw great site (i love the design!)