jQuery change event on checkbox

April 6th, 2010

A lot of times, you’ll want to call a javascript function when a checkbox is changed from unchecked to check and vice versa.  Up until the release of jQuery 1.4, the obvious way to do it (the jQuery .change() event) did not work properly across all versions of Internet Explorer.  Instead, you had to check for the .click() event.  This was an accessibility problem because it did not fire when a user changed a checkbox with the space bar instead of by clicking.  Well, now we can rejoice.  The following code snippet works exactly how you think it would across browsers, including IE.

<!-- Load jQuery, and the necessary html -->
<script type='text/javascript src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<input type='checkbox' name='my_checkbox' value='true' checked='checked'>
$(document).ready(function(){
  1.     $(":checkbox").change(function(){
  2.         if($(this).attr("checked"))
  3.         {
  4.             //call the function to be fired
  5.             //when your box changes from
  6.             //unchecked to checked
  7.         }
  8.         else
  9.         {
  10.             //call the function to be fired
  11.             //when your box changes from
  12.             //checked to unchecked
  13.         }
  14.     });
  15. });

View Demo

Leave a Reply