April 3, 2012
javascript multiple checkbox validation
Question by skylab
I would like to use this simple script with my form to make sure I have at least 1 box checked but I have a feeling something is wrong, most likely at the getElementsByName tag. I always get the pop up box no matter if I have items checked or not.
<script language="javascript">
function validate() {
var chks = document.getElementsByName('id[][]');
var hasChecked = false;
for (var i = 0; i < chks.length; i++) {
if (chks[i].checked) {
hasChecked = true;
break;
}
}
if (hasChecked == false) {
alert("Please select at least one.");
return false;
}
return true;
}
</script>
and the form, which may or may not end up with more checkboxes in the end:
<form
enctype="multipart/form-data"
method="post"
action="formsubmission.php"
name="form_type" onSubmit="return validate()">
<input id="attrib-8-10" type="checkbox" value="10" name="id[8][10]">
<label class="Checkbox" for="attrib-8-10">thick</label>
<input id="attrib-8-11" type="checkbox" value="11" name="id[8][11]">
<label class="Checkbox" for="attrib-8-11">medium</label>
<input id="attrib-8-12" type="checkbox" value="12" name="id[8][12]">
<label class="Checkbox" for="attrib-8-12">thin</label>
Answer by Starx
var chks = document.getElementsByName('id[][]');
Does not select any element, as you have specied all the index on the elements .
Here is how you can do it?
var chks= document.getElementsByTagName('input');
for (var x=0; x < chks.length; x++) {
if (chks[x].type.toUpperCase()=='CHECKBOX' && chks[x].checked == true) {
hasChecked = true;
break;
}
}