In this article I will explain with an example, how to validate ASP.Net CheckBoxList control and check whether at-least one CheckBox is checked using JavaScript.
HTML Markup
The HTML Markup consists of an ASP.Net CheckBoxList control and a Button control.
The ASP.Net Button has been assigned an OnClientClick event handler in which the name of JavaScript function has been specified which will perform the validation.
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Text="One" Value="1"></asp:ListItem>
<asp:ListItem Text="Two" Value="2"></asp:ListItem>
<asp:ListItem Text="Three" Value="3"></asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:Button ID="Button1" runat="server" Text="Validate" OnClientClick="return Validate()" />
Implementing CheckBoxList validation using JavaScript
Inside the Validate JavaScript function, first the CheckBoxList and its internal CheckBoxes are referenced.
Then, a loop is executed over the CheckBoxes to check whether the CheckBox is checked.
If at-least one CheckBox is checked then the validation is successful else an error message is displayed using JavaScript Alert Message Box.
<script type="text/javascript">
function Validate() {
var checkBoxList = document.getElementById("<%=CheckBoxList1.ClientID%>");
var checkBoxes = checkBoxList.getElementsByTagName("input");
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
return true;
}
}
alert("Please select atleast one item.");
return false;
}
</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