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.


