Setting "checked" for a checkbox with jQuery

Created 08.01.2009 22:20
Viewed 3.44M times
4298 votes

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?

7
Comments
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. by Peter Krauss, 09.03.2012 12:36
Check other ways to do this using jQuery here stackoverflow.com/a/22019103/1868660 by Subodh Ghulaxe, 25.02.2014 15:46
If you need the onchange event triggered, it's $("#mycheckbox").click(); by HumanInDisguise, 11.05.2015 14:06
"Checking something" suggests testing it, so I think 'Making a checkbox checked' is a more clear and better title. by Alireza, 12.05.2015 17:26
prop(); function is the perfect answer. See the function definition - api.jquery.com/prop by yogihosting, 23.05.2016 15:01
attr() doesnot work with IE. using prop() is the best option by divine, 26.04.2017 10:52
$(".myCheckBox").prop("checked", true) by Tal, 20.09.2019 07:56
Show remaining 2 comments
Answers 42
19
6157

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.

08.01.2009 22:25
Comments
Is this getting the value or setting the value? How do I uncheck it? by tpower, 08.01.2009 22:40
Yes this is setting the attribute value, and uncheck by removing the attribute. I have updated my answer to show this. by Xian, 08.01.2009 22:48
@Xian removing the the checked attribute makes it impossible to reset the form by mcgrailm, 23.03.2011 15:27
Problem here is if you need something that works for both versions. In that case, you can use the plugin. :) Thanks for the update! by cwharris, 06.05.2011 21:12
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(...) by cwharris, 13.05.2011 20:08
"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... by Tyler Crompton, 30.03.2012 09:32
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. by Katie Kilian, 04.05.2012 16:28
not sure if this applies with jQuery too, but just in case stackoverflow.com/questions/10650233/… by ajax333221, 31.05.2012 19:56
don't forget to put # in front of the id. by User, 11.09.2012 15:28
@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 by gnarf, 01.10.2012 23:35
bchhun's answer is the more correct one, the .prop method will not affect the element that is submitted on form submit by srcspider, 15.11.2012 09:35
in jQuery 1.9 you MUST use prop('checked', bool) because of changes in behavior : jquery.com/upgrade-guide/1.9 by Simon_Weaver, 31.01.2013 20:25
$('.myCheckbox').removeAttr('checked'); will not work after the user has clicked on the check box. Instead, see my answer stackoverflow.com/a/5916151/696056 by cwharris, 13.03.2013 19:22
If things don't toggle they way you want, specifically on Chrome (things going nicely on FF and even IE7,8), use native access $('.myCheckbox')[0].checked=true and take a look at this one: stackoverflow.com/q/5907645#answer-5907877 by Frank Nocke, 12.09.2013 17:12
UPD: To check checkbox input via jQuery use .is() method with ':checked' selector - to check all described methods above and dependency on jQuery version see: jsfiddle.net/sF8Kk by dr.dimitru, 21.10.2013 17:15
The name of this property is easier to understand when one realises 'checked' is the US word for 'ticked'. (This is also the etymology behind the term 'checkbox'.) (The years I spent living in the US has helped me make sense of a lot of nomenclature quirks in programming languages.) by Michael Scheper, 05.04.2015 00:23
Changing the value ignored the .change(...) handler I had set up, I just added on: $(this).attr('checked',!this.checked).change() by Pluto, 28.04.2016 19:38
Finally after googling for half an hour, it was so simple like this (actually I knew it should be simple). I was trying to undo the checkbox state inside change event, if the user decided to cancel the operation with a prompt dialog. This works without event.preventDefault() and other stuff people suggested in other answers. by Alisson, 07.07.2016 01:30
Note: this doesn't trigger the change event. Add .trigger('change') if needed by the_nuts, 16.04.2017 18:30
Show remaining 14 comments
6
736

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');
08.01.2009 22:25
Comments
also $(selector).checked to check is checked by eomeroff, 02.05.2011 23:56
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. by JD Smith, 28.03.2013 01:26
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. by YuriAlbuquerque, 11.10.2013 15:27
@YuriAlbuquerque it was an example. you can use whatever selector you want. by bchhun, 13.10.2013 00:14
$(selector).checked does not work. There is no 'checked' method in jQuery. by SineSwiper, 07.10.2015 16:42
@BrendanByrd There's a checked property on the DOM object though (without the jQuery wrapping) by bchhun, 13.10.2015 17:55
Show remaining 1 comments
6
324

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;
});
06.05.2011 19:31
Comments
In your first JSFiddle example you should be using removeAttr('checked') rather than attr('checked', false) by Daniel X Moore, 30.01.2012 07:00
@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. by cwharris, 30.01.2012 13:28
@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) by Daniel X Moore, 02.02.2012 01:45
Yes. prop is definitely the appropriate way to set attributes on an element. by cwharris, 02.02.2012 02:40
@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 by Joe Johnston, 04.03.2014 03:59
@JoeJohnston In a perfect world, that shouldn't be built into the plugin. Instead, it should be converted to a true/false value before being using with the plugin. What's to say a database doesn't consider '0' true? It all depends on the database. by cwharris, 07.03.2014 21:42
Show remaining 1 comments
5
151

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()
});
08.01.2009 22:24
Comments
you can also go $("#myTable input:checkbox").each(...); by Chris Brandsma, 08.01.2009 22:37
You can also go $(".myCheckbox").click() by RobertPitt, 20.09.2010 11:49
@Michah removing the the checked attribute makes it impossible to reset the form by mcgrailm, 23.03.2011 15:32
This answer is out-of-date because it uses .attr instead of .prop. by Blazemonger, 21.01.2014 14:15
$("#mycheckbox").click(); worked for me as I was listening to change event too and .attr & .prop didn't fire change event. by Damodar Bashyal, 01.05.2017 06:30
2
82

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.

20.08.2010 18:19
Comments
@livfree75 removing the the checked attribute makes it impossible to reset the form by mcgrailm, 23.03.2011 15:32
This answer is out-of-date because it uses .attr instead of .prop. by Blazemonger, 21.01.2014 14:16
3
66
$("#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.

08.01.2009 22:36
Comments
top one will fail...checked is not a jquery object member by redsquare, 09.01.2009 00:20
This answer is out-of-date because it uses .attr instead of .prop. by Blazemonger, 21.01.2014 14:16
IMO the click event is unreliable in Firefox and Edge. by Vahid Amiri, 31.08.2019 11:21
12
63

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');
    }
});
23.03.2011 15:22
Comments
This is inaccurate. setting the 'checked' attribute to '' will not uncheck check boxes in at least chrome. by cwharris, 06.05.2011 05:58
@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 by mcgrailm, 06.05.2011 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 by mcgrailm, 06.05.2011 20:10
mcgralim - in 1.6 its even easier.... $(".mycheckbox").prop("checked", true/false) by gnarf, 06.05.2011 20:11
@gnarf thats great but now i'll have to go change that in all my code 8 ^ ( by mcgrailm, 06.05.2011 20:14
@mcgrailm - its still not released, but we may be adding some backwards compat for .attr() with boolean attributes -- although I wish we wouldn't -- Read: forum.jquery.com/topic/prop-attr-rewrite-again by gnarf, 06.05.2011 20:18
@Blazemonger do you mean you use .prop rather than .attr ? by mcgrailm, 21.01.2014 14:20
Your answer promised a new up-to-date solution, which you never provided. .attr has been the wrong approach to this problem for more than two years now. by Blazemonger, 21.01.2014 14:25
I did post a corrected answer at the time but that was 4 years ago dude. I don't go around updating all my posts and I'm sure most people don't. You down vote was for a post 4 years old saying it's out of date, well duh by mcgrailm, 21.01.2014 14:29
@DaveRager in this case, though, the obsolete answers are not only obsolete, but also completely redundant since the accepted answer covers their content fine already. There's no point in updating an obsolete answer if afterwards it will still not be useful. by Mark Amery, 14.12.2014 23:43
@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. by mcgrailm, 15.12.2014 14:50
@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. by Mark Amery, 15.12.2014 16:54
Show remaining 7 comments
0
53

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.

20.09.2010 11:43
1
46

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

if ($('#myCheckBox:checked').val() !== undefined)
{
    //Checked
}
else
{
    //Not checked
}
24.06.2012 11:33
Comments
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. by Mark Amery, 14.12.2014 23:47
0
47

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);
09.03.2012 12:28
0
43

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);
14.03.2013 09:40
0
38

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>

23.10.2012 00:41
1
32

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;
    });
});
25.10.2011 08:51
Comments
This answer is out-of-date because it uses .attr instead of .prop. by Blazemonger, 21.01.2014 14:18
1
30

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');
24.06.2011 08:27
Comments
This answer is out-of-date because it uses .attr instead of .prop. by Blazemonger, 21.01.2014 14:18
0
31

Try this:

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

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

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.

17.04.2012 06:34
1
26

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;
        }
    }
});
16.08.2013 06:17
Comments
-​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. by Mark Amery, 15.12.2014 18:33
4
14

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
05.01.2012 13:26
Comments
shouldn't it be true and false and not 'true' and 'false'? by tpower, 05.01.2012 15:34
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. by Shadow The Vaccinated Wizard, 24.06.2012 11:41
@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. by Mark Amery, 15.12.2014 18:46
use true and false values for boolean, do not use 'true' or 'false' (strings). by Jone Polvora, 21.02.2015 22:34
0
22

Another possible solution:

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

To check and uncheck

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
14.11.2013 06:34
Comments
-​1; this adds no value at all to an already bloated thread. The code here is exactly the same as the accepted answer. by Mark Amery, 15.12.2014 18:25
3
18

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

22.05.2013 07:25
Comments
This is irrelevant, since all the (correct) answers use .prop('checked',true). by Blazemonger, 21.01.2014 14:19
Not sure I understood your comment.This still exists in jQuery documentation. Are you implying there is no memory leak in IE < 9 ? by naor, 21.01.2014 20:53
There is no memory leak in this case, since we are setting it to a simple primitive value (Boolean). by Blazemonger, 21.01.2014 20:56
0
19

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");
11.01.2013 13:05
0
20

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();
23.09.2016 18:43
0
19

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');
21.04.2015 10:29
1
17
$('controlCheckBox').click(function(){
    var temp = $(this).prop('checked');
    $('controlledCheckBoxes').prop('checked', temp);
});
16.07.2013 02:10
Comments
-​1 for being a code-only answer, not answering the question directly, and adding nothing that other answers hadn't already covered. by Mark Amery, 15.12.2014 18:28
0
16

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.

27.05.2014 15:11
1
15

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

18.09.2013 01:14
Comments
@MarkAmery The accepted answer does not cover how to do it without jQuery. My answer adds supplementary benefit to the accepted answer. by Alex W, 15.12.2014 20:12
2
10

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");
}
10.06.2013 13:17
Comments
This does not answer the question. by Samuel Liew, 10.06.2013 13:20
This answer is out-of-date because it uses .attr instead of .prop. by Blazemonger, 21.01.2014 14:20
0
12

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
    });
27.02.2013 15:49
0
14

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.

05.03.2015 13:10
1
11

In case you use ASP.NET MVC, generate many checkboxes and later have to select/unselect all using JavaScript you can do the following.

HTML

@foreach (var item in Model)
{
    @Html.CheckBox(string.Format("ProductId_{0}", @item.Id), @item.IsSelected)
}

JavaScript

function SelectAll() {       
        $('input[id^="ProductId_"]').each(function () {          
            $(this).prop('checked', true);
        });
    }

    function UnselectAll() {
        $('input[id^="ProductId_"]').each(function () {
            $(this).prop('checked', false);
        });
    }
08.07.2014 18:22
Comments
Why is the each needed here? by tpower, 09.07.2014 14:58
0
10

This may help someone.

HTML5

 <input id="check_box" type="checkbox" onclick="handleOnClick()">

JavaScript.

  function handleOnClick(){

      if($("#check_box").prop('checked'))
      {        
          console.log("current state: checked");
      }
      else
      {         
          console.log("current state: unchecked");
      }    
 }
29.09.2016 13:55
1
7
$(".myCheckBox").prop("checked","checked");
13.05.2013 09:50
Comments
This answer is out-of-date because it uses .attr instead of .prop. by Blazemonger, 21.01.2014 14:21
0
6

You can try this:

$('input[name="activity[task_state]"]').val("specify the value you want to check ")
23.04.2014 06:34
1
8

if($('jquery_selector').is(":checked")){
  //somecode
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

01.11.2017 13:19
Comments
When giving an answer it is preferable to give some explanation as to WHY your answer is the one. by Stephen Rauch, 01.11.2017 13:48
1
7

If you are using .prop('checked', true|false) and don’t have changed checkbox, you need to add trigger('click') like this:

// Check
$('#checkboxF1').prop( "checked", true).trigger('click');


// Uncheck
$('#checkboxF1').prop( "checked", false).trigger('click');
15.09.2018 17:57
Comments
so happy that I found this. thank you! almost went nuts!! by pangyuteng, 08.08.2020 02:10
0
6

You can check a checkbox checked condition using JavaScript in different ways. You can see below.

  1. First method - $('.myCheckbox').prop('checked', true);

  2. Second method - $('.myCheckbox').attr('checked', true);

  3. Third method (for check condition if checkbox is checked or not) - $('.myCheckbox').is(':checked')

01.12.2017 07:08
0
5

If you happen to be using Bootstrap (perhaps unawarely) ...

$('#myCheckbox').bootstrapToggle('on')
$('#myCheckbox').bootstrapToggle('off')

http://www.bootstraptoggle.com/

14.03.2017 20:32
0
5

Edited on 2019 January

You can use: .prop( propertyName ) - version added: 1.6

p {margin: 20px 0 0;}
b {color: red;}
label {color: red;}
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check here</label>
<p></p>
 
<script>
$( "input" ).change(function() {
  var $input = $( this );
  $( "p" ).html(
    "The .attr( \"checked\" ): <b>" + $input.attr( "checked" ) + "</b><br>" +
    "The .prop( \"checked\" ): <b>" + $input.prop( "checked" ) + "</b><br>" +
    "The .is( \":checked\" ): <b>" + $input.is( ":checked" ) + "</b>" );
}).change();
</script>
 
</body>
</html>

On Angular Framework

Example 1

In your .html file

<input type="checkbox" (change)="toggleEditable($event)">

In your .ts file

toggleEditable(event) {
     if ( event.target.checked ) {
         this.contentEditable = true;
    }
}

Example 2

In your .html file

<input type="checkbox" [(ngModel)]="isChecked" (change)="checkAction(isChecked ? 'Action1':'Action2')" />
02.01.2019 15:10
1
1

A JavaScript solution can be also simple and with less overhead:

document.querySelectorAll('.myCheckBox').forEach(x=> x.checked=1)

document.querySelectorAll('.myCheckBox').forEach(x=> x.checked=1)
checked A: <input type="checkbox" class="myCheckBox"><br/>
unchecked: <input type="checkbox"><br/>
checked B: <input type="checkbox" class="myCheckBox"><br/>

27.12.2019 21:53
Comments
This belongs on Check/Uncheck checkbox with JavaScript (jQuery or Vanilla)? or JavaScript check multiple checkbox, not this jQuery question. by Heretic Monkey, 27.12.2019 22:03
0
1

You can do this if you have the id to check it

document.getElementById('ElementId').checked = false

And this to uncheck

document.getElementById('ElementId').checked = true

04.12.2020 12:15
0
-6

For overall:

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