In this article I will explain with an example, how to use JavaScript with CheckBoxList in ASP.Net.
This article will explain how to validate CheckBoxList to check whether its Item is selected or not and also how to get the Text and Value of the selected CheckBox using JavaScript in ASP.Net.
 
 

HTML Markup

The HTML Markup consists of following controls:
CheckBoxList – For capturing user input.
The CheckBoxList consists of three ListItems.
Button – For validating and displaying Text and Value of selected CheckBox.
The Button has been assigned with an OnClientClick event handler for calling Validate JavaScript function.
<asp:CheckBoxList ID="chkNumbers" 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="btnValidate" runat="server" Text="Validate" OnClientClick="return Validate()" />
 
 

Validating CheckBoxList and Displaying Text and Value of the selected CheckBox using JavaScript

When Validate Button is clicked, the following JavaScript function gets called.
Inside this Validate JavaScript function, first the reference of the CheckBoxList, the CheckBoxes inside the CheckBoxList and Label elements are referenced.
A FOR loop is executed over the referenced CheckBoxes and each CheckBox is validated whether it is checked.
If checked then, its Text and Value is fetched and displayed using JavaScript alert Message Box.
If none of the CheckBoxes is checked, then a JavaScript Alert Message Box is displayed with a message informing the user that he has to select at least single CheckBox from the ASP.Net CheckBoxList.
<script type="text/javascript">
    function Validate() {
        var atLeast = 1
        var checkBoxList = document.getElementById("<%=chkNumbers.ClientID%>");
        var checkBoxes = checkBoxList.getElementsByTagName("input");
        var counter = 0;
        var message = "";
        for (var i = 0; i < checkBoxes.length; i++) {
            if (checkBoxes[i].checked) {
                var value = checkBoxes[i].value;
                var text = checkBoxes[i].parentNode.getElementsByTagName("LABEL")[0].innerHTML;
                message += "Value: " + value + " Text: " + text;
                message += "\n";
                counter++;
           }
        }
 
        if (atLeast > counter) {
            alert("Please select atleast " + atLeast + " item(s).");
        } else {
            alert(message);
        }
 
        return false;
    }
</script>
 
 

Screenshot

Using JavaScript with ASP.Net CheckBoxList Control
 
 

Browser Compatibility

The above code has been tested in the following browsers.
Microsoft Edge  FireFox  Chrome  Safari  Opera 
* All browser logos displayed above are property of their respective owners.
 
 

Demo

 
 

Download