tpower
tpower

Reputation: 56866

Setting "checked" for a checkbox with jQuery

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?

Upvotes: 4600

Views: 3880713

Answers (30)

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11045

I was wondering why none of the old answers mentioned that to fully simulate the ticking, you also need to simulate the change event if you want to fire something else after simulating ticking:

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

Upvotes: 5

cwharris
cwharris

Reputation: 18125

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

Upvotes: 363

vnapastiuk
vnapastiuk

Reputation: 659

If you consider using vanilla js instead of jquery there is a solution:

//for one element: 
document.querySelector('.myCheckBox').checked = true /* or false */ //will select the first matched element
//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
checkbox.checked = true //or false
}

Upvotes: 1

Omar Odeh
Omar Odeh

Reputation: 43

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

Upvotes: 2

Kenmeister
Kenmeister

Reputation: 504

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

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

http://www.bootstraptoggle.com/

Upvotes: 6

Gaurang Sondagar
Gaurang Sondagar

Reputation: 834

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

Upvotes: 7

Alex Montoya
Alex Montoya

Reputation: 5089

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

Upvotes: 10

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92347

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

Upvotes: 1

Xian
Xian

Reputation: 76591

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.

Upvotes: 6448

L Y E S  -  C H I O U K H
L Y E S - C H I O U K H

Reputation: 5080

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

Upvotes: 6

Abou-Emish
Abou-Emish

Reputation: 2321

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.

Upvotes: 56

tech savy
tech savy

Reputation: 193

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

Upvotes: 9

David Arul
David Arul

Reputation: 171

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

Upvotes: 11

Ardalan Shahgholi
Ardalan Shahgholi

Reputation: 12555

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

Upvotes: 23

Ramon de Jesus
Ramon de Jesus

Reputation: 788

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

Upvotes: 45

starjahid
starjahid

Reputation: 357

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

Upvotes: 34

Prasanth P
Prasanth P

Reputation: 715

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

Upvotes: 31

SedJ601
SedJ601

Reputation: 13859

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

Upvotes: 11

Xitalogy
Xitalogy

Reputation: 1612

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>

Upvotes: 40

tamilmani
tamilmani

Reputation: 591

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

Upvotes: 27

logan
logan

Reputation: 8346

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

Upvotes: 20

bchhun
bchhun

Reputation: 18474

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

Upvotes: 783

Serhat Koroglu
Serhat Koroglu

Reputation: 1275

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.

Upvotes: 15

fredcrs
fredcrs

Reputation: 3621

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

Upvotes: 14

Friedrich
Friedrich

Reputation: 2290

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.

Upvotes: 16

Overbeeke
Overbeeke

Reputation: 2028

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

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

Upvotes: 48

NoWar
NoWar

Reputation: 37633

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

Upvotes: 12

naor
naor

Reputation: 3650

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

Upvotes: 18

Muhammad Aamir Ali
Muhammad Aamir Ali

Reputation: 21087

Another possible solution:

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

Upvotes: 23

Peter Krauss
Peter Krauss

Reputation: 13920

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

Upvotes: 51

Related Questions