How do I check a checkbox with jQuery?
23
I want to do something like this

or 

I wish to set the value.

Is such a thing built into jQuery?
improve this question | comment
Quentin Jerde Created at: 2013-11-13 17:07:34 UTC By Quentin Jerde
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. - Reyes Koss
Note: the problem only exists in jQuery 1.6. - Otis Aufderhar
@xixonia - I updated the accepted answer to have the correct information for jQuery 1.6 - Oma Barton
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. - Ms. Jaquelin Lueilwitz
27 Answers
0
$(".myCheckBox").attr("checked","checked");

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

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

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

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


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

$('form #mycheckbox').is(':checked');

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

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

0
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.
0
$("#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.
0
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');
    }
});

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

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

0
Try this:

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

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

0
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

0
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>

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

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

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

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

0
$('controlCheckBox').click(function(){
    var temp = $(this).prop('checked');
    $('controlledCheckBoxes').prop('checked', temp);
});

0
here is the code  and demo for to check multiple check box..

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

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

    var chk = document.getElementById('check').checked;

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

0
For overall:

$("#checkAll").click(function(){
    $(".somecheckBoxes").prop('checked',$(this).prop('checked')?true:false);
});

0
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
0
Another possible solution:

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

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

Your Answer