Click toggle with jQuery

This is easily done by flipping the current ‘checked’ state of the checkbox upon each click. Examples:

 $(".offer").on("click", function () { 
       var $checkbox = $(this).find(':checkbox');
       $checkbox.attr('checked', !$checkbox.attr('checked'));
 });

or:

 $(".offer").on("click", function () { 
       var $checkbox = $(this).find(':checkbox');
       $checkbox.attr('checked', !$checkbox.is(':checked'));
 });

or, by directly manipulating the DOM ‘checked’ property (i.e. not using attr() to fetch the current state of the clicked checkbox):

 $(".offer").on("click", function () { 
       var $checkbox = $(this).find(':checkbox');
       $checkbox.attr('checked', !$checkbox[0].checked);
 });

…and so on.

Note: since jQuery 1.6, checkboxes should be set using prop not attr:

 $(".offer").on("click", function () { 
       var $checkbox = $(this).find(':checkbox');
       $checkbox.prop('checked', !$checkbox[0].checked);
 });

Leave a Comment