2 Feb
2009

ASP.Net CheckBox and JQuery

Category:UncategorizedTag: , :

A funny thing happened on the way to to forum today…wait, wrong talk.

Here something I’ve been dealing a lot with lately, the ASP.Net Checkbox control and JQuery.  Also, the HTML checkbox and JQuery.  OK, Checkboxes and JQuery.

Problem is you don’t always get what you think you are going to get, and there are multiple ways of dealing with that.  So let us start with the basics:  you have checkboxes, and you want the client (html+javascript) to do something when the checkbox is checked/unchecked.  Simple.

First thing out of the gate, lets look at the asp:CheckBox control.  This is generally converted to a <input type=’checkbox’ /> — but not exactly like that.  In fact, there are several variations you can get depending on what properties you have set.  Here are the ones I know about.

The properties that I am going to highlight are Text, CssClass, and TextAlign. Here are five check boxes, followed by the html that results from those properties being set or not.

<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" runat="server" Text="Test 2" />
<asp:CheckBox ID="CheckBox3" runat="server" CssClass="CheckBoxClass" />
<asp:CheckBox ID="CheckBox4" runat="server" Text="Test 4" CssClass="CheckBoxClass" />
<asp:CheckBox ID="CheckBox5" runat="server" Text="Test 5" CssClass="CheckBoxClass" TextAlign="Left" />
<input id="CheckBox1" type="checkbox" name="CheckBox1" />
<input id="CheckBox2" type="checkbox" name="CheckBox2" /><label for="CheckBox2">Test 2</label>
<span class="CheckBoxClass"><input id="CheckBox3" type="checkbox" name="CheckBox3" /></span>
<span class="CheckBoxClass"><input id="CheckBox4" type="checkbox" name="CheckBox4" /><label for="CheckBox4">Test 4</label></span>
<span class="CheckBoxClass"><label for="CheckBox5">Test 5</label><input id="CheckBox5" type="checkbox" name="CheckBox5" /></span>

Notice anything different or unexpected?  How about this one: I set the CssClass, which adds a Span tag to the mix, and the CssClass is assigned to the Span.  This can be absolute havoc for JavaScript developers if you don’t know it is coming.  You get your site working, then you get a requirement to add some text to a checkbox, and your JavaScript suddenly stops working.  Hopefully you notice.

Now, being a JQuery kind of guy, now do I find the checkboxes in each of these cases?

Hang up #1

First off: are you using MasterPages?  Heck, even if you are not, you should get into a habit — always grab the controls IDs from the code behind.  From my code above you can see that I’m not using MasterPages, the names are not prefixed with the name of the masterpage and content panel.  But it is still a good habit for when dealing with generated code.

Say I want the ID of the first checkbox.  In my aspx code it is CheckBox1.  But if you want to get that value (which can be mangled by MasterPages), you should use this  <%=CheckBox1.ClientID  %> in your JavaScript.

Now, lets get the first checkbox: The first one is easy: 

var checkbox1 = $("#<%= CheckBox1.ClientID %>");

Checkbox 2 is the same, assuming you don’t want to change the text or anything tricky like that.  But the code is ugly.  So for CheckBox2 I’m going to break things out a bit:

var checkbox2Name = "#<%= CheckBox2.ClientID %>";  
var checkbox2 = $(checkbox2Name);

For CheckBox3 and CheckBox4 you could write the same code.  But I want both checkboxes.  In fact, I want all checkboxes with the css class CheckBoxClass assigned to them.  That is a little different.

var checkboxes = $(".CheckBoxClass input[type='checkbox']");   

OK, now what?

We now have all of the CheckBoxes…so what?  Actually there are a lot of things we might want to do from here.  Each checkbox has several DOM properties that are of interest.  There is the onclick event, the Checked property, and the Click method.

Hooking up the onclick event is easy:

checkboxes.onclick = function() { alert('Hi there:'+ this.attr('ID')); };

Now, any time a checkbox is checked, or unchecked, a message will display “Hi there” with the name of the control that was clicked.  I can also programmatically make this happen with this code:

checkboxes.click();

Which will check or uncheck any of the checkboxes (toggles each of them individually), and fire the onclick event.  So for our example, you should see two message boxes saying “Hi there” when done.  This is such happy code.

Hang up #2: the checked property

Each checkbox has a checked property as well.  Seems simple enough to grab that value from it.  Like this:

var isChecked = checkbox1.checked;

Unfortunately that does not work.  If you inspect the value of isChecked you will get ‘unassigned’ which is the JavaScript version of ‘I have no idea what you are talking about’.

The issue is with what JQuery returns you: arrays.  All JQuery selectors return arrays. Here is the code for CheckBox1 again:

var checkbox1 = $("#<%= CheckBox1.ClientID %>");

checkbox1 is not a DOM element.  It is an array.   If we want the actual DOM element, we need to get it from the array:

var checkbox1 = $("#<%= CheckBox1.ClientID %>");
var domCheckbox1 = checkbox1[0];
var isChecked = domCheckbox1.checked;

Cool, now we can finally get the checked property!  We now have the ability to do some cool things.

Check All unchecked

$(".CheckBoxClass input[type='checkbox']").each(function(){
           if (!this.checked)
                $(this).click();
});

The cool part is this code only checks the checkboxes that are unchecked.  But we can actually make this better.

In JQuery there are a number of custom attributes you can take advantage of.  Two that I’m thinking of right now are :checkbox, :checked, and :not.   :checkbox only returns checkboxes.  :checked only returns any checked element, and :not returns the inverse of something.  So I can take the code above, and rewrite it like this:

$(".CheckBoxClass:checkbox:not(:checked)").click();
Then, to do the opposite:
$(".CheckBoxClass:checkbox:checked").click();

One thing with JavaScript, Less code is Elegant Code.  And this is a lot less code, and is still more readable than a regular expression.

If you are not familiar with all of the different attribute selectors in JQuery, please take a look at the site documentation: http://docs.jquery.com/Selectors.  It is quite amazing what they have in there.

Wrap up

OK, that is enough of an introduction to checkboxes and JQuery.  Hopefully that clears some things up for you.  Have fun.

9 thoughts on “ASP.Net CheckBox and JQuery

  1. Hi this is just what I’m looking for! However I cannot get a checkbox (or a radiobutton) to select/unselect a collection of other checkboxes. I think it’s my .net code because of all the span tags added after I have put a CssClass for each checkbox.

    I don’t suppose you could throw up a demo page?

    Thanks

  2. You solved my problem!!! 100% !!!! I will be linking this from my blog, I was racking my brain as to why I was getting an undefined on my ‘checkbox’… Once I saw your part about the array.. it was like a huge slap! I dont know why I didnt realize it… Thanks SO much

Comments are closed.