In this article I will explain how to validate ASP.Net CheckBoxList control and check whether at least one CheckBox is checked using JavaScript at client side.

Below is the CheckBoxList I am using for this article

<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>

 

Concept

The ASP.Net CheckBoxList Control when rendered Client Side page it is rendered as HTML Table with CheckBoxes in it. Refer the figure below.

ASP.Net CheckBoxList rendered as HTML table with CheckBoxes

Hence we will need to write a script which will loop through all the controls (CheckBoxes) in the generated HTML table in order to validate or get the selected Item

Now when you do a research of the HTML Source you get the following

ASP.Net CheckBoxList renders the Text part within label tags

You can see above in the yellow mark that the Text is rendered between <label> tags.

 

Validating CheckBoxList using JavaScript

Below is the JavaScript function to perform validations in an ASP.Net CheckBoxList control.

<script type = "text/javascript">

var atLeast = 1

function Validate()

{

   var CHK = document.getElementById("<%=CheckBoxList1.ClientID%>");

   var checkbox = CHK.getElementsByTagName("input");

   var counter=0;

   for (var i=0;i<checkbox.length;i++)

   {

       if (checkbox[i].checked)

       {

            counter++;

       }

   }

   if(atLeast>counter)

   {

        alert("Please select atleast " + atLeast +  " item(s)");

        return false;

   }

   return true;

}

</script>

 

You will notice I am simply looping through all the input controls (CheckBoxes) and checking whether it is checked and incrementing the counter variable. Finally I match its value with the atLeast variable. If the atLeast value is greater than the counter variable it prompts the user to select the required number of items when user selects an item the page is submitted

The above JavaScript method is called on the click of a button given below

<asp:Button ID="Button1" runat="server" Text="Validate" OnClientClick =

"return Validate()" />



Validate ASP.Net CheckBoxList control (at least one checked) using JavaScript

The above code has been tested in the following browsers

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.



Demo

View Demo


Downloads

JavaScriptWithCheckBoxlist.zip