Setting "checked" for a checkbox with jQuery

Asked 2023-09-20 20:06:07 View 253,178

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?

  • A more specific (and very useful!) question, "How do I check a item in a checkbox-set BY VALUE?", I think we can also discuss here, and I posted an answer below. - anyone
  • Check other ways to do this using jQuery here stackoverflow.com/a/22019103/1868660 - anyone
  • If you need the onchange event triggered, it's $("#mycheckbox").click(); - anyone
  • "Checking something" suggests testing it, so I think 'Making a checkbox checked' is a more clear and better title. - anyone
  • prop(); function is the perfect answer. See the function definition - api.jquery.com/prop - anyone

Answers

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.

Answered   2023-09-20 20:06:07

  • @Xian removing the the checked attribute makes it impossible to reset the form - anyone
  • As a side note, jQuery 1.6.1 should be fixing the issue I mentioned, so we can tehcnically all still go back to using $(...).prop(...) - anyone
  • "If you're working with just one element, it will always be fastest to use DOMElement.checked = true". But it would be negligible, because it's only one element... - anyone
  • As Tyler says, it is a negligible improvement in performance. To me, coding using a common API makes it more readable than mixing native API and jQuery APIs. I'd stick with jQuery. - anyone
  • @TylerCrompton - Of course, its not entirely about performance, but doing $(element).prop('checked') is a complete waste of typing. element.checked exists and should be used in the cases where you already have element - anyone

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');

Answered   2023-09-20 20:06:07

  • also $(selector).checked to check is checked - anyone
  • I tried this exact code and it didn't work for me in the case of a select all / select none checkbox that needs to check and uncheck all as well as check their state. Instead, I tried @Christopher Harris' answer and that did the trick. - anyone
  • Why using "form #mycheckbox" instead of simply "#mycheckbox"? The id is already unique in the whole document, it is faster and simpler to pick it directly. - anyone
  • @YuriAlbuquerque it was an example. you can use whatever selector you want. - anyone
  • $(selector).checked does not work. There is no 'checked' method in jQuery. - anyone

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;
});

Answered   2023-09-20 20:06:07

  • In your first JSFiddle example you should be using removeAttr('checked') rather than attr('checked', false) - anyone
  • @DanielXMoore, You're skirting around the issue. The example was to show that once the check-box was clicked by the user, the browser no longer responds to checked attribute changes, regardless of the method used to change them. - anyone
  • @ChristopherHarris Ok, you're right, I missed that. As of jQuery 1.6 shouldn't you use the .prop method though?$('.myCheckBox').prop('checked', true) That way it will automatically apply to the entire set of matched elements (only when setting though, getting is still only the first) - anyone
  • Yes. prop is definitely the appropriate way to set attributes on an element. - anyone
  • @ChristopherHarris, I have added what I needed to the plugin to allow some parameter flexibility. This made inline processing easier without the type conversion. Esp from disparate databases with 'ideas' about what "true" is. Fiddle: jsfiddle.net/Cyberjetx/vcp96 - anyone

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()
});

Answered   2023-09-20 20:06:07

  • you can also go $("#myTable input:checkbox").each(...); - anyone
  • You can also go $(".myCheckbox").click() - anyone
  • @Michah removing the the checked attribute makes it impossible to reset the form - anyone
  • This answer is out-of-date because it uses .attr instead of .prop. - anyone
  • $("#mycheckbox").click(); worked for me as I was listening to change event too and .attr & .prop didn't fire change event. - anyone

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.

Answered   2023-09-20 20:06:07

  • @livfree75 removing the the checked attribute makes it impossible to reset the form - anyone
  • This answer is out-of-date because it uses .attr instead of .prop. - anyone
$("#mycheckbox")[0].checked = true;
$("#mycheckbox").attr('checked', true);
$("#mycheckbox").click();

The last one will fire the click event for the checkbox, the others will not. So if you have custom code in the onclick event for the checkbox that you want to fire, use the last one.

Answered   2023-09-20 20:06:07

  • top one will fail...checked is not a jquery object member - anyone
  • This answer is out-of-date because it uses .attr instead of .prop. - anyone
  • IMO the click event is unreliable in Firefox and Edge. - anyone

To check a checkbox you should use

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

or

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

and to uncheck a check box you should always set it to false:

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

If you do

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

it removes the attribute all together and therefore you will not be able to reset the form.

BAD DEMO jQuery 1.6. I think this is broken. For 1.6 I am going to make a new post on that.

NEW WORKING DEMO jQuery 1.5.2 works in Chrome.

Both demos use

$('#tc').click(function() {
    if ( $('#myCheckbox').attr('checked')) {
        $('#myCheckbox').attr('checked', false);
    } else {
        $('#myCheckbox').attr('checked', 'checked');
    }
});

Answered   2023-09-20 20:06:07

  • This is inaccurate. setting the 'checked' attribute to '' will not uncheck check boxes in at least chrome. - anyone
  • @xixonia I did test before I posted your fiddle doesn't work because you didn't change the menu on the left to include jquery - anyone
  • mcgralim - in 1.6 its even easier.... $(".mycheckbox").prop("checked", true/false) - anyone
  • @MarkAmery you mentioned that my post added nothing at the time of post but that is in accurate. If you look at the history of the accepted answer you'll find they suggest removing the element. Which makes it impossible to reset the form, which was why I posted to begin with. - anyone
  • @mcgrailm I've gone ahead and modified the accepted answer in light of your remarks. If you'd like to cast an eye over it and check that it looks good in its current state, I'd appreciate that. My apologies again for offering up sharp criticism that was, at least in part, highly misguided. - anyone

This selects elements that have the specified attribute with a value containing the given substring "ckbItem":

$('input[name *= ckbItem]').prop('checked', true);

It will select all elements that contain ckbItem in its name attribute.

Answered   2023-09-20 20:06:07

Assuming that the question is...

How do I check a checkbox-set BY VALUE?

Remember that in a typical checkbox set, all input tags have the same name, they differ by the attribute value: there are no ID for each input of the set.

Xian's answer can be extended with a more specific selector, using the following line of code:

$("input.myclass[name='myname'][value='the_value']").prop("checked", true);

Answered   2023-09-20 20:06:07

I'm missing the solution. I'll always use:

if ($('#myCheckBox:checked').val() !== undefined)
{
    //Checked
}
else
{
    //Not checked
}

Answered   2023-09-20 20:06:07

  • This doesn't answer the question (the question is about setting whether a checkbox is checked, not determining whether a checkbox is checked). It's also a pretty ugly way of determining if the checkbox is checked (for one thing, you're exploiting the non-self-evident fact that .val() will always return undefined when called on 0 elements to detect that a jQuery object is empty, when you could simply check its .length instead) - see stackoverflow.com/questions/901712/… for more readable approaches. - anyone

To check a checkbox using jQuery 1.6 or higher just do this:

checkbox.prop('checked', true);

To uncheck, use:

checkbox.prop('checked', false);

Here' s what I like to use to toggle a checkbox using jQuery:

checkbox.prop('checked', !checkbox.prop('checked'));

If you're using jQuery 1.5 or lower:

checkbox.attr('checked', true);

To uncheck, use:

checkbox.attr('checked', false);

Answered   2023-09-20 20:06:07

Here is a way to do it without jQuery

function addOrAttachListener(el, type, listener, useCapture) {
  if (el.addEventListener) {
    el.addEventListener(type, listener, useCapture);
  } else if (el.attachEvent) {
    el.attachEvent("on" + type, listener);
  }
};

addOrAttachListener(window, "load", function() {
  var cbElem = document.getElementById("cb");
  var rcbElem = document.getElementById("rcb");
  addOrAttachListener(cbElem, "click", function() {
    rcbElem.checked = cbElem.checked;
  }, false);
}, false);
<label>Click Me!
  <input id="cb" type="checkbox" />
</label>
<label>Reflection:
  <input id="rcb" type="checkbox" />
</label>

Answered   2023-09-20 20:06:07

Here is code for checked and unchecked with a button:

var set=1;
var unset=0;
jQuery( function() {
    $( '.checkAll' ).live('click', function() {
        $( '.cb-element' ).each(function () {
            if(set==1){ $( '.cb-element' ).attr('checked', true) unset=0; }
            if(set==0){ $( '.cb-element' ).attr('checked', false); unset=1; }
        });
        set=unset;
    });
});

Update: Here is the same code block using the newer Jquery 1.6+ prop method, which replaces attr:

var set=1;
var unset=0;
jQuery( function() {
    $( '.checkAll' ).live('click', function() {
        $( '.cb-element' ).each(function () {
            if(set==1){ $( '.cb-element' ).prop('checked', true) unset=0; }
            if(set==0){ $( '.cb-element' ).prop('checked', false); unset=1; }
        });
        set=unset;
    });
});

Answered   2023-09-20 20:06:07

  • This answer is out-of-date because it uses .attr instead of .prop. - anyone

Try this:

$('#checkboxid').get(0).checked = true;  //For checking

$('#checkboxid').get(0).checked = false; //For unchecking

Answered   2023-09-20 20:06:07

We can use elementObject with jQuery for getting the attribute checked:

$(objectElement).attr('checked');

We can use this for all jQuery versions without any error.

Update: Jquery 1.6+ has the new prop method which replaces attr, e.g.:

$(objectElement).prop('checked');

Answered   2023-09-20 20:06:07

  • This answer is out-of-date because it uses .attr instead of .prop. - anyone

If you are using PhoneGap doing application development, and you have a value on the button that you want to show instantly, remember to do this

$('span.ui-[controlname]',$('[id]')).text("the value");

I found that without the span, the interface will not update no matter what you do.

Answered   2023-09-20 20:06:07

Here is the code and demo for how to check multiple check boxes...

http://jsfiddle.net/tamilmani/z8TTt/

$("#check").on("click", function () {

    var chk = document.getElementById('check').checked;
    var arr = document.getElementsByTagName("input");

    if (chk) {
        for (var i in arr) {
            if (arr[i].name == 'check') arr[i].checked = true;
        }
    } else {
        for (var i in arr) {
            if (arr[i].name == 'check') arr[i].checked = false;
        }
    }
});

Answered   2023-09-20 20:06:07

  • -​1; mixing jQuery selectors like $("#check") with raw DOM API calls like document.getElementsByTagName("input") seems inelegant to me, especially given that the for loops here could be avoided by using .prop(). Regardless this is yet another late answer that adds nothing new. - anyone

Another possible solution:

    var c = $("#checkboxid");
    if (c.is(":checked")) {
         $('#checkboxid').prop('checked', false);
    } else {
         $('#checkboxid').prop('checked', true);
    }

Answered   2023-09-20 20:06:07

As @livefree75 said:

jQuery 1.5.x and below

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));

But in new versions of jQuery, we have to use something like this:

jQuery 1.6+

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

Then you can just do:

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

Answered   2023-09-20 20:06:07

For jQuery 1.6+

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

For jQuery 1.5.x and below

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

To check,

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

Answered   2023-09-20 20:06:07

If using mobile and you want the interface to update and show the checkbox as unchecked, use the following:

$("#checkbox1").prop('checked', false).checkboxradio("refresh");

Answered   2023-09-20 20:06:07

To check and uncheck

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

Answered   2023-09-20 20:06:07

  • -​1; this adds no value at all to an already bloated thread. The code here is exactly the same as the accepted answer. - anyone

Be aware of memory leaks in Internet Explorer prior to Internet Explorer 9, as the jQuery documentation states:

In Internet Explorer prior to version 9, using .prop() to set a DOM element property to anything other than a simple primitive value (number, string, or boolean) can cause memory leaks if the property is not removed (using .removeProp()) before the DOM element is removed from the document. To safely set values on DOM objects without memory leaks, use .data().

Answered   2023-09-20 20:06:07

  • This is irrelevant, since all the (correct) answers use .prop('checked',true). - anyone
  • Not sure I understood your comment.This still exists in jQuery documentation. Are you implying there is no memory leak in IE < 9 ? - anyone
  • There is no memory leak in this case, since we are setting it to a simple primitive value (Boolean). - anyone
$('controlCheckBox').click(function(){
    var temp = $(this).prop('checked');
    $('controlledCheckBoxes').prop('checked', temp);
});

Answered   2023-09-20 20:06:07

  • -​1 for being a code-only answer, not answering the question directly, and adding nothing that other answers hadn't already covered. - anyone

This is probably the shortest and easiest solution:

$(".myCheckBox")[0].checked = true;

or

$(".myCheckBox")[0].checked = false;

Even shorter would be:

$(".myCheckBox")[0].checked = !0;
$(".myCheckBox")[0].checked = !1;

Here is a jsFiddle as well.

Answered   2023-09-20 20:06:07

Plain JavaScript is very simple and much less overhead:

var elements = document.getElementsByClassName('myCheckBox');
for(var i = 0; i < elements.length; i++)
{
    elements[i].checked = true;
}

Example here

Answered   2023-09-20 20:06:07

  • @MarkAmery The accepted answer does not cover how to do it without jQuery. My answer adds supplementary benefit to the accepted answer. - anyone

When you checked a checkbox like;

$('.className').attr('checked', 'checked')

it might not be enough. You should also call the function below;

$('.className').prop('checked', 'true')

Especially when you removed the checkbox checked attribute.

Answered   2023-09-20 20:06:07

I couldn't get it working using:

$("#cb").prop('checked', 'true');
$("#cb").prop('checked', 'false');

Both true and false would check the checkbox. What worked for me was:

$("#cb").prop('checked', 'true'); // For checking
$("#cb").prop('checked', '');     // For unchecking

Answered   2023-09-20 20:06:07

  • shouldn't it be true and false and not 'true' and 'false'? - anyone
  • It "didn't work" because 'false' was converted to boolean value which resulted in true - empty string evaluates to false thus it "worked". See this fiddle for example of what I mean. - anyone
  • @chris97ong I've rolled back your edit; when someone says "Don't use the code below because it doesn't work", fixing that code while leaving the comment saying that it doesn't work is harmful - especially when it breaks the explanation in the comments of why the code isn't working. That said, this answer is still somewhat confused and deserves a downvote for the reasons given by tpower and ShadowWizard. - anyone
  • use true and false values for boolean, do not use 'true' or 'false' (strings). - anyone

Here's the complete answer using jQuery

I test it and it works 100% :D

    // when the button (select_unit_button) is clicked it returns all the checed checkboxes values 
    $("#select_unit_button").on("click", function(e){

             var arr = [];

             $(':checkbox:checked').each(function(i){
                 arr[i] = $(this).val(); // u can get id or anything else
             });

              //console.log(arr); // u can test it using this in google chrome
    });

Answered   2023-09-20 20:06:07

In jQuery,

if($("#checkboxId").is(':checked')){
    alert("Checked");
}

or

if($("#checkboxId").attr('checked')==true){
    alert("Checked");
}

In JavaScript,

if (document.getElementById("checkboxID").checked){
    alert("Checked");
}

Answered   2023-09-20 20:06:07

  • This does not answer the question. - anyone
  • This answer is out-of-date because it uses .attr instead of .prop. - anyone