In this article I will explain with an example, how to validate Group of CheckBoxes (Multiple CheckBoxes) using JavaScript.
When the Submit Button is clicked, all the CheckBoxes in the Group will be referenced and using FOR loop, it will be validated that at-least one CheckBox is checked from the Group of CheckBoxes using JavaScript.
HTML Markup
The HTML Markup consist of an HTML Table with a Group of CheckBoxes to be validated, an HTML SPAN for displaying the error message and a HTML Button.
The HTML Button has been assigned a JavaScript OnClick event handler.
<table id = "tblFruits" border="0" cellpadding="0" cellspacing="0">
<tr>
<td><input type="checkbox" value="1" /></td>
<td>Mango</td>
</tr>
<tr>
<td><input type="checkbox" value="2" /></td>
<td>Apple</td>
</tr>
<tr>
<td><input type="checkbox" value="3" /></td>
<td>Banana</td>
</tr>
<tr>
<td><input type="checkbox" value="4" /></td>
<td>Grapes</td>
</tr>
<tr>
<td><input type="checkbox" value="5" /></td>
<td>Orange</td>
</tr>
</table>
<br />
<span id="spnError" class="error" style="display: none">Please select at-least one Fruit.</span>
<br />
<input type="button" value="Submit" onclick="return Validate()" />
JavaScript function to validate Group of CheckBoxes (Multiple CheckBoxes)
When the Submit Button is clicked, first the HTML Table is referenced and then all the CheckBoxes inside the Table are referenced.
Then using FOR loop, each CheckBox is verified whether it is checked.
If at-least one CheckBox is checked, then the validation is successful else an error message is displayed using JavaScript.
<script type="text/javascript">
function Validate() {
//Reference the Table containing Group of CheckBoxes.
var table = document.getElementById("tblFruits");
//Reference the Group of CheckBoxes.
var checkBoxes = table.getElementsByTagName("input");
//Set the Valid Flag to False initially.
var isValid = false;
//Loop and verify whether at-least one CheckBox is checked.
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].type == "checkbox" && checkBoxes[i].checked) {
isValid = true;
break;
}
}
//Display error message if no CheckBox is checked.
document.getElementById("spnError").style.display = isValid ? "none" : "block";
return isValid;
}
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads