JQuery Stuff

I was the “bug person” the other day, (which means that I get to fix bugs for the day) when I came across a bug involving a check box.  Basically, the check box didn’t work.  Clicking on the check box caused the page to refresh and remain unchecked.  As I dug into the JQuery code that was attached to the check box click event, I found something rather interesting.  There are a lot of ways to check a check box to see if it is checked or not.  The code that was used was by the section of code I was fixing was incorrect.

First, the HTML code:

<input type=”checkboxid=”MyCheckBox” />My Check Box

Next, the JQuery:

$(document).ready(function () {
  $(‘#MyCheckBox‘).click(function () {

    var test1 = $(‘#MyCheckBox‘).prop(‘checked’);
    var test2 = $(‘#MyCheckBox‘).attr(‘checked’);
    var test3 = $(‘#MyCheckBox‘).checked;

  });

});

The question here is what are the results of “test1”, “test2” and “test3” when the check box is checked?  As it turns out, test1 is the only valid output (returning true).  The other two will return an “undefined” output.

The problem with test2 is that there is no “checked” attribute defined in the html.  So let’s define it:

<input type=”checkbox” id=”MyCheckBoxchecked=”checked” />My Check Box

Now the results have changed.  First, the check box is already checked (due to the fact that the html tells it to be checked).  Second, test2 now returns “checked” instead of undefined.  Check1 returns false, as expected and test3 still returns “undefined”.

At this point, you can see where the attr is returning the attribute of checked (which is normally equal to “checked” or “”).  If you perform a true/false comparison with this value, you will get some iffy results.  To guarantee a true false, use the following code:

if ($(“#MyCheckBox“).is(“:checked“)) {
  alert(‘checked‘);
}
else {
  alert(‘unchecked‘);

}

This will give the correct true/false results.

Of course, using the property method also guarantees a true/false result:

if ($(“#MyCheckBox“).prop(“checked“)) {
  alert(‘checked‘);
}
else {
  alert(‘unchecked‘);

}

Test3 does not work under any of these samples.  I would avoid using it.  I personally use the “prop” or property to check for true/false, because I don’t have to worry about the colon that is required when using the “is” statement.  it’s very clean and simple.  I also leave the checked=”checked” off the check box, unless I need to initialize it to true to start with.

The bug I was fixing used the attr inside an if statement and assumed that true/false was the result.  I changed it to use the property instead, and now there is one less bug.  😉

 

0 thoughts on “JQuery Stuff

  1. I wonder if the apparently useless ". checked" is a known jQuery bug or it is only designed to work on specific contexts or what. Anyway, as my first exposure to jQuery, this doesn't exactly fill. me with confidence.

Leave a Reply