Validate ASP.NET CheckboxList using jQuery

ASP.NET CheckBoxList is group of checkboxes which is used to create a multi-selection check box group. In this post, I will show you how to validate ASP.NET CheckBoxList using jQuery.

Let's declare a CheckboxList.

<asp:CheckBoxList ID="CheckBoxList1" runat="server">
    <asp:ListItem Text="Singing" Value="Singing"></asp:ListItem>
    <asp:ListItem Text="Writing" Value="Writing"></asp:ListItem>
    <asp:ListItem Text="Travelling" Value="Travelling"></asp:ListItem>
    <asp:ListItem Text="Blogging" Value="Blogging"></asp:ListItem>
    <asp:ListItem Text="Sports" Value="Sports"></asp:ListItem>
</asp:CheckBoxList>

As you can see there are 5 checkboxes and the validation would be to select at least 3 technologies. And on click of button, validate the checkboxlist. To find out, how many checkboxes are checked, use length property to find out.

$("#CheckBoxList1 input:checked").length; will give count of checked checkboxes out of the list.

$(document).ready(function() {
    $('#btnSubmit').on('click', function(e) {
        var cnt = $("#CheckBoxList1 input:checked").length;
        if (cnt < 3) 
        {
            alert('Select at least 3 technologies');
            e.preventDefault();
        }
        else 
            alert('Well Done!!!!');
    });
});?

Note: This code will work only with jQuery 1.7 or higher version as I have used .on() method to bind the click event and .on was introduced in jQuery 1.7. So if you are using below version then you can either .live() or .bind() method.

Suggested Post,

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...