Setting "checked" for a checkbox with jQuery

3,603,810

Solution 1

Modern jQuery

Use .prop():

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

DOM API

If you're working with just one element, you can always just access the underlying HTMLInputElement and modify its .checked property:

$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;

The benefit to using the .prop() and .attr() methods instead of this is that they will operate on all matched elements.

jQuery 1.5.x and below

The .prop() method is not available, so you need to use .attr().

$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);

Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using $('.myCheckbox').removeAttr('checked'); since the latter will, if the box was initially checked, change the behaviour of a call to .reset() on any form that contains it – a subtle but probably unwelcome behaviour change.

For more context, some incomplete discussion of the changes to the handling of the checked attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop() documentation.

Solution 2

Use:

$(".myCheckbox").attr('checked', true); // Deprecated
$(".myCheckbox").prop('checked', true);

And if you want to check if a checkbox is checked or not:

$('.myCheckbox').is(':checked');

Solution 3

This is the correct way of checking and unchecking checkboxes with jQuery, as it is cross-platform standard, and will allow form reposts.

$('.myCheckBox').each(function(){ this.checked = true; });

$('.myCheckBox').each(function(){ this.checked = false; });

By doing this, you are using JavaScript standards for checking and unchecking checkboxes, so any browser that properly implements the "checked" property of the checkbox element will run this code flawlessly. This should be all major browsers, but I am unable to test previous to Internet Explorer 9.

The Problem (jQuery 1.6):

Once a user clicks on a checkbox, that checkbox stops responding to the "checked" attribute changes.

Here is an example of the checkbox attribute failing to do the job after someone has clicked the checkbox (this happens in Chrome).

Fiddle

The Solution:

By using JavaScript's "checked" property on the DOM elements, we are able to solve the problem directly, instead of trying to manipulate the DOM into doing what we want it to do.

Fiddle

This plugin will alter the checked property of any elements selected by jQuery, and successfully check and uncheck checkboxes under all circumstances. So, while this may seem like an over-bearing solution, it will make your site's user experience better, and help prevent user frustration.

(function( $ ) {
    $.fn.checked = function(value) {
        if(value === true || value === false) {
            // Set the value of the checkbox
            $(this).each(function(){ this.checked = value; });
        } 
        else if(value === undefined || value === 'toggle') {
            // Toggle the checkbox
            $(this).each(function(){ this.checked = !this.checked; });
        }

        return this;
    };
})( jQuery );

Alternatively, if you do not want to use a plugin, you can use the following code snippets:

// Check
$(':checkbox').prop('checked', true);

// Un-check
$(':checkbox').prop('checked', false);

// Toggle
$(':checkbox').prop('checked', function (i, value) {
    return !value;
});

Solution 4

You can do

$('.myCheckbox').attr('checked',true) //Standards compliant

or

$("form #mycheckbox").attr('checked', true)

If you have custom code in the onclick event for the checkbox that you want to fire, use this one instead:

$("#mycheckbox").click();

You can uncheck by removing the attribute entirely:

$('.myCheckbox').removeAttr('checked')

You can check all checkboxes like this:

$(".myCheckbox").each(function(){
    $("#mycheckbox").click()
});

Solution 5

You can also extend the $.fn object with new methods:

(function($)  {
   $.fn.extend({
      check : function()  {
         return this.filter(":radio, :checkbox").attr("checked", true);
      },
      uncheck : function()  {
         return this.filter(":radio, :checkbox").removeAttr("checked");
      }
   });
}(jQuery));

Then you can just do:

$(":checkbox").check();
$(":checkbox").uncheck();

Or you may want to give them more unique names like mycheck() and myuncheck() in case you use some other library that uses those names.

Share:
3,603,810
tpower
Author by

tpower

Updated on July 19, 2022

Comments

  • tpower
    tpower almost 2 years

    I'd like to do something like this to tick a checkbox using jQuery:

    $(".myCheckBox").checked(true);
    

    or

    $(".myCheckBox").selected(true);
    

    Does such a thing exist?