By tpower


2009-01-08 22:20:24 8 Comments

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?

30 comments

@Lyes CHIOUKH 2019-01-02 15:10:04

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')" />

@Gaurang Sondagar 2017-12-01 07:08:53

You can check checkbox checked condition using JS 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')

@Alex Montoya 2018-09-15 17:57:26

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

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


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

@Abou-Emish 2010-09-20 11:43:08

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.

@Xian 2009-01-08 22:25:08

jQuery 1.6+

Use the new .prop() method:

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

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.

Any version of jQuery

If you're working with just one element, you can always just modify the HTMLInputElement's .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.

@tpower 2009-01-08 22:40:37

Is this getting the value or setting the value? How do I uncheck it?

@Xian 2009-01-08 22:48:52

Yes this is setting the attribute value, and uncheck by removing the attribute. I have updated my answer to show this.

@mcgrailm 2011-03-23 15:27:32

@Xian removing the the checked attribute makes it impossible to reset the form

@mcgrailm 2011-03-23 15:38:29

my answer below shows how to get around that

@cwharris 2011-05-06 21:12:57

Problem here is if you need something that works for both versions. In that case, you can use the plugin. :) Thanks for the update!

@cwharris 2011-05-13 20:08:53

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

@Tyler Crompton 2012-03-30 09:32:56

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

@Charlie Kilian 2012-05-04 16:28:15

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.

@ajax333221 2012-05-31 19:56:02

not sure if this applies with jQuery too, but just in case stackoverflow.com/questions/10650233/…

@user1382306 2012-09-11 15:28:33

don't forget to put # in front of the id.

@gnarf 2012-10-01 23:35:23

@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

@srcspider 2012-11-15 09:35:24

bchhun's answer is the more correct one, the .prop method will not affect the element that is submitted on form submit

@Simon_Weaver 2013-01-31 20:25:56

in jQuery 1.9 you MUST use prop('checked', bool) because of changes in behavior : jquery.com/upgrade-guide/1.9

@cwharris 2013-03-13 19:22:06

$('.myCheckbox').removeAttr('checked'); will not work after the user has clicked on the check box. Instead, see my answer stackoverflow.com/a/5916151/696056

@Frank Nocke 2013-09-12 17:12:00

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

@dr.dimitru 2013-10-21 17:15:02

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

@Michael Scheper 2015-04-05 00:23:36

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

@Pluto 2016-04-28 19:38:48

Changing the value ignored the .change(...) handler I had set up, I just added on: $(this).attr('checked',!this.checked).change()

@Alisson 2016-07-07 01:30:25

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.

@Ashiquzzaman 2017-04-14 05:38:03

I am using jQuery 3.1.1 and it's work for me.

@the_nuts 2017-04-16 18:30:57

Note: this doesn't trigger the change event. Add .trigger('change') if needed

@Marcus Hiles 2019-02-14 18:51:56

This worked for me. Thanks

@mathew 2013-05-13 09:50:11

$(".myCheckBox").prop("checked","checked");

@Halcyon 2013-07-24 16:49:46

The attr() function will not work for multiple toggles.

@Blazemonger 2014-01-21 14:21:15

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

@David Arul 2017-11-01 13:19:52

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

@Stephen Rauch 2017-11-01 13:48:47

When giving an answer it is preferable to give some explanation as to WHY your answer is the one.

@Ardalan Shahgholi 2016-09-23 18:43:14

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

@Ramon de Jesus 2013-03-14 09:40:12

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

@starjahid 2011-10-25 08:51:47

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

@Blazemonger 2014-01-21 14:18:56

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

@Prasanth P 2011-06-24 08:27:21

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

@Blazemonger 2014-01-21 14:18:19

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

@Kenmeister 2017-03-14 20:32:38

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

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

http://www.bootstraptoggle.com/

@Sedrick 2016-09-29 13:55:54

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

@Aeoril 2012-10-23 00:41:23

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>

@tamilmani 2013-08-16 06:17:37

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

@Mark Amery 2014-12-15 18:33:08

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

@cwharris 2011-05-06 19:31:21

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

@Daniel X Moore 2012-01-30 07:00:08

In your first JSFiddle example you should be using removeAttr('checked') rather than attr('checked', false)

@cwharris 2012-01-30 13:28:29

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

@Daniel X Moore 2012-02-02 01:45:40

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

@cwharris 2012-02-02 02:40:32

Yes. prop is definitely the appropriate way to set attributes on an element.

@Joe Johnston 2014-03-04 03:59:27

@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

@cwharris 2014-03-07 21:42:55

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

@logan 2015-04-21 10:29: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');

@bchhun 2009-01-08 22:25:25

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

@eomeroff 2011-05-02 23:56:23

also $(selector).checked to check is checked

@JD Smith 2013-03-28 01:26:21

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.

@YuriAlbuquerque 2013-10-11 15:27:03

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.

@bchhun 2013-10-13 00:14:28

@YuriAlbuquerque it was an example. you can use whatever selector you want.

@Brendan Byrd 2015-10-07 16:42:39

$(selector).checked does not work. There is no 'checked' method in jQuery.

@bchhun 2015-10-13 17:55:27

@BrendanByrd There's a checked property on the DOM object though (without the jQuery wrapping)

@Serhat Koroglu 2015-03-05 13:10:51

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.

@fredcrs 2012-01-05 13:26:52

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

@fredcrs 2012-01-05 13:27:40

using jquery 1.7-min

@tpower 2012-01-05 15:34:05

shouldn't it be true and false and not 'true' and 'false'?

@Shadow Wizard 2012-06-24 11:41:31

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.

@Mark Amery 2014-12-15 18:46:12

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

@Jone Polvora 2015-02-21 22:34:07

use true and false values for boolean, do not use 'true' or 'false' (strings).

@frieder 2014-05-27 15:11:43

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.

@Overbeeke 2012-06-24 11:33:42

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

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

@Mark Amery 2014-12-14 23:47:58

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.

@Developer 2014-07-08 18:22:56

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

@tpower 2014-07-09 14:58:28

Why is the each needed here?

@naor 2013-05-22 07:25:31

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

@Blazemonger 2014-01-21 14:19:37

This is irrelevant, since all the (correct) answers use .prop('checked',true).

@naor 2014-01-21 20:53:17

Not sure I understood your comment.This still exists in jQuery documentation. Are you implying there is no memory leak in IE < 9 ?

@Blazemonger 2014-01-21 20:56:35

There is no memory leak in this case, since we are setting it to a simple primitive value (Boolean).

@Muhammad Aamir Ali 2013-10-12 08:23:42

Another possible solution:

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

@Peter Krauss 2012-03-09 12:28:49

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

@anusha 2014-04-23 06:34:58

You can try this:

$('input[name="activity[task_state]"]').val("specify the value you want to check ")

@ijarlax 2013-06-10 13:17:51

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

@Samuel Liew 2013-06-10 13:20:10

This does not answer the question.

@Blazemonger 2014-01-21 14:20:34

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

@jj2422 2013-11-14 06:34:53

To check and uncheck

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

@Mark Amery 2014-12-15 18:25:36

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

@Alex W 2013-09-18 01:14: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

@Alex W 2014-12-15 20:12:47

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

Related Questions

Sponsored Content

53 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

3 Answered Questions

70 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

34 Answered Questions

[SOLVED] $(document).ready equivalent without jQuery

  • 2009-04-28 21:51:11
  • FlySwat
  • 916429 View
  • 1798 Score
  • 34 Answer
  • Tags:   javascript jquery

60 Answered Questions

[SOLVED] How to check whether a checkbox is checked in jQuery?

34 Answered Questions

[SOLVED] Add table row in jQuery

40 Answered Questions

[SOLVED] Is there an "exists" function for jQuery?

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 704414 View
  • 2541 Score
  • 40 Answer
  • Tags:   javascript jquery

33 Answered Questions

15 Answered Questions

[SOLVED] "Thinking in AngularJS" if I have a jQuery background?

Sponsored Content