Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to do something like this

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

or

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

I wish to set the value.

Is such a thing built into jQuery?

share|improve this question
11  
I have added an answer below that solves what I believe to be a serious problem with the answer chosen, and all of the other answers given. When a user manually clicks the checkbox, the checkbox will fail to be set using the Attr solution in chrome and firefox, and internet explorer. This will most likely cause a bad user experience. I've posted an example, as well as a solution to the problem, and it matches your question almost exactly. – Christopher Harris May 6 '11 at 19:50
Note: the problem only exists in jQuery 1.6. – Christopher Harris May 6 '11 at 20:24
@xixonia - I updated the accepted answer to have the correct information for jQuery 1.6 – gnarf May 6 '11 at 21:05
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. – Peter Krauss Mar 9 '12 at 12:36

22 Answers

up vote 1507 down vote accepted

It certainly is in

jQuery 1.6+

Use the new .prop() function:

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

jQuery 1.5 and below

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

To check the checkbox (by setting the value of the checked attribute) do

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

and for un-checking (by removing the attribute entirely) do

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

Any version of jQuery

If you're working with just one element, it will always be fastest to use DOMElement.checked = true. The benefit to using the .prop() and .attr() functions is that they will operate on all matched elements.

// Assuming an event handler on a checkbox
if (this.checked)
share|improve this answer
3  
@Xian removing the the checked attribute makes it impossible to reset the form – mcgrailm Mar 23 '11 at 15:27
19  
Just a heads up. Since jQuery 1.6 this has changed and is no longer viable. Take a look at .attr and .prop. – Marcus Ekwall May 6 '11 at 7:22
1  
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(...) – Christopher Harris May 13 '11 at 20:08
3  
"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... – Tyler Crompton Mar 30 '12 at 9:32
5  
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. – Charlie Kilian May 4 '12 at 16:28
show 14 more comments

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()
});
share|improve this answer
you can also go $("#myTable input:checkbox").each(...); – Chris Brandsma Jan 8 '09 at 22:37
You can also go $(".myCheckbox").click() – RobertPitt Sep 20 '10 at 11:49
@Michah removing the the checked attribute makes it impossible to reset the form – mcgrailm Mar 23 '11 at 15:32
$("form #mycheckbox").attr('checked', true);

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

$('form #mycheckbox').is(':checked');
share|improve this answer
3  
Checking for a value of 'checked' is considered more standards-compliant as per Xian's answer. – cletus Jan 8 '09 at 22:31
This is what I wanted to know : How to test when it is checked. Thanks. – JohnnyBizzle Oct 28 '10 at 12:38
1  
Nice examples here electrictoolbox.com/check-uncheck-checkbox-jquery – Pavlo Neyman Dec 29 '10 at 18:33
1  
also $(selector).checked to check is checked – eomeroff May 2 '11 at 23:56
thx its works for me :) – manish nautiyal Jun 12 '12 at 9:19
show 1 more comment
$("#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.

share|improve this answer
2  
top one will fail...checked is not a jquery object member – redsquare Jan 9 '09 at 0:20
i think you meant $("#mycheckbox")[0].checked for the first one, but i havent verified that for sure – Simon_Weaver Feb 2 '09 at 5:27
1  
You are correct, and I fixed the error. Thank you. – Chris Brandsma Feb 3 '09 at 17:07
1  
click(), I like it. – Tim Jun 19 '12 at 1:54
+1‭‭‭‭‭‭‭‭‭‭‭‭‭ – uınbɐɥs Sep 18 '12 at 23:21

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|improve this answer
3  
@livfree75 removing the the checked attribute makes it impossible to reset the form – mcgrailm Mar 23 '11 at 15:32

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

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

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

share|improve this answer

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');
    }
});
share|improve this answer
1  
This is inaccurate. setting the 'checked' attribute to '' will not uncheck check boxes in at least chrome. – Christopher Harris May 6 '11 at 5:58
@xixonia thanks for pointing that out I think that worked at one time i have edited my post – mcgrailm May 6 '11 at 13:26
@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 – mcgrailm May 6 '11 at 18:44
@xixonia thanks again, It seems this doesn't work the same way in jauery 1.6 see note above thanks for adding your solution as well – mcgrailm May 6 '11 at 20:10
1  
mcgralim - in 1.6 its even easier.... $(".mycheckbox").prop("checked", true/false) – gnarf May 6 '11 at 20:11
show 4 more comments

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

http://jsfiddle.net/xixonia/zgcrB/

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.

http://jsfiddle.net/xixonia/WnbNC/

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;
});
share|improve this answer
4  
+1... setAttribute is the devil. – canon May 6 '11 at 20:10
2  
In your first JSFiddle example you should be using removeAttr('checked') rather than attr('checked', false) – Daniel X Moore Jan 30 '12 at 7:00
1  
@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. – Christopher Harris Jan 30 '12 at 13:28
3  
@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) – Daniel X Moore Feb 2 '12 at 1:45
1  
Nice little plugin, thanks! To maintain chainability, add "return this" just before the end of the plugin. – JD Smith Mar 28 at 2:47
show 3 more comments

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.

share|improve this answer

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;
    });
});
share|improve this answer

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
share|improve this answer
using jquery 1.7-min – fredcrs Jan 5 '12 at 13:27
4  
shouldn't it be true and false and not 'true' and 'false'? – tpower Jan 5 '12 at 15:34
2  
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. – Shadow Wizard Jun 24 '12 at 11:41

Assuming that the question is "How do I check a checkbox-set BY VALUE?"...

Remember that in a checkbox set all input tags have the same name, they differ by value, and you can not (neither elegantly or usefully) use a ID for each one.

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);
share|improve this answer

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.

share|improve this answer

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

if ($('#myCheckBox:checked').val() !== undefined)
{
    //Checked
}
else
{
    //Not checked
}
share|improve this answer
This made an easy work. Thanks mate... – Frank Jul 9 '12 at 7:56

Try this:

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

$('#checkboxid').get(0).checked = false; //For unchecking
share|improve this answer

Here is a way to do it without jQuery - live sample:

JavaScript:

(function () {

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

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>setCheck Example</title>
</head>
<body>
    <label>Click Me! <input id="cb" type="checkbox" /></label>
    <label>Reflection: <input id="rcb" type="checkbox" /></label>
    <script type="text/javascript" src="setCheck.js"></script>
</body>
</html>
share|improve this answer

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");
share|improve this answer

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
    });
share|improve this answer

To check a checkbox using jQuery 1.9 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'));
share|improve this answer
$(".myCheckBox").attr("checked","checked");
share|improve this answer

Be aware of memory leaks in IE prior to IE9, 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().

share|improve this answer

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");
}
share|improve this answer
This does not answer the question. – Samuel Liew Jun 10 at 13:20

protected by NullPoiиteя Jun 10 at 5:05

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

Not the answer you're looking for? Browse other questions tagged or ask your own question.