Skip to content
Fix Code Error

Setting “checked” for a checkbox with jQuery

March 13, 2021 by Code Error
Posted By: tpower

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?

Solution

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.

Answered By: Xian

Related Articles

  • Is CSS Turing complete?
  • Polymer 1.x: Observers
  • getting text input from a form in react.js using Refs
  • Examples of GoF Design Patterns in Java's core libraries
  • Customize Bootstrap checkboxes
  • Adding Max to a Result After Group By
  • Get all variables sent with POST?
  • Show/hide 'div' using JavaScript
  • Paper checkbox and -webkit-column-count
  • Polymer 1.x: Databinding Arrays

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I get the number of elements in a list?

Next Post:

How do I sort a dictionary by value?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error