How to select checkboxes in an ASP.NET CheckBoxList using jQuery

I came across a situation where I needed to make sure at least one checkbox in an ASP.NET CheckBoxList is checked before submitting the page.  Looking at the source each checkbox element created shares the same client ID with a different number at the end, so I needed a way to select all checkboxes where the ID started the same.

The ‘wilcard’ select I needed can be done using the jQuery Attribute Starts With Selector to get all elements that start with the ClientID of my CheckBoxList.  Once I have these element I then need to filter them down to the checkbox input elements as the CheckBoxList also renders other elements starting with the same ID. I can do this by also using the Checkbox Selector.

I have put my jQuery inside my ASP.NET page so I can easily get the CheckBoxList’s ClientID using ASP server tags.  The following line would get all the checkbox elements in the CheckBoxList:

var checkboxes = $("[id^=<%= CheckBoxList1.ClientID %>"]:checkbox);

In my code I needed to check if any items were checked when the form is submitted and if not show an error message and prevent the form from submitting.  Here is the full code to do this:


$().ready(function() {
    $("#<%=btnSubmit.ClientID %>").bind("click", function() {
        var valid = false;
        $("[id^=<%= CheckBoxList1.ClientID %>"]:checked).each(function() {
            if ($(this).is(":checked")) {
                valid = true;
                return false;
            }
        });

        if (valid) {
            $("#lblErrorMessage").hide();
        }
        else {
            $("#lblErrorMessage").show();
        }

        return valid;
    });
});

Here you can see that I am looping through each checkbox and then using the jQuery Is method to check if the item is checked. If so I’m setting my valid variable to true and returning false. Returning false inside a jQuery each loop exits the loop.  I then show or hide my error message then return the valid variable which if false, prevent the form from submitting.

This all works but I could refactor it further to include the Checked selector with my other selectors and avoid using an each loop:

var valid = $("[id^=<%= cblPaymentMethods.ClientID %>]:checkbox:checked").length > 0;

Here I am getting the number of checked checkboxes in the CheckBoxList, which if zero means nothing is selected and form is invalid.

Posted on by Joe in ASP.NET, jQuery

5 Responses to How to select checkboxes in an ASP.NET CheckBoxList using jQuery

  1. Jamie

    Do you know how I can show an error message when all of my checkboxes have been chosen already? My checkboxes are dynamically pulled into a modal, which allows features to be added. When all features are added and the modal is empty, I need an error message to tell the user that all features have been assigned.

  2. Joe

    Hi Jamie

    There are a couple of ways you could do it. One way would be to hook up to each checkbox’s change event, then compare the number of checkboxes with the number of checked checkboxes.

    Here is a jQuery function that would do it for a CheckBoxList with the ID cblFeature and a Label with ID lblMessage. I’ve set the ClientIDMode to static.


    $().ready(function () {
    $("[id^=cblFeature]:checkbox").change(function () {
    var checkboxCount = $("[id^=cblFeature]:checkbox").length;
    var checkedCount = $("[id^=cblFeature]:checkbox:checked").length;

    if (checkboxCount == checkedCount) {
    $("#lblMessage").html("All features selected");
    } else {
    $("#lblMessage").html(" ");
    }
    });
    });

    Cheers
    Joe

  3. John rob

    Really this is a good article, which helps a lot for beginners as me as well as developer. Thanks for sharing with us. Check out this helpful link too its also having nice post with wonderful explanation on CheckBoxList Control in ASP.Net….

    http://mindstick.com/Articles/75f78330-82ff-4989-b06b-2975933209a7/?CheckBoxList%20Control%20in%20ASP.Net

    Thanks

  4. adam

    Thats really good thanks what does the little ^ arrow do by the way? I have had success in the past with a checkbox list accessing using the name if the checkbox list was not generated server side you can just give the checkboxes the same name then this code will work:

    $(“[name=grpExistingJob]:checked”).each(function() {
    });

  5. Joe

    Adam

    It’s the ‘starts with’ jQuery selector (http://api.jquery.com/attribute-starts-with-selector/)

    In this instance all ids will start with the client id of the check box list, so it ensures it gets all check boxes in the list.

    Cheers
    Joe

Add a Comment