Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 685
tpower Avatar asked Jan 08 '09 22:01

tpower


People also ask

How do you set checkbox is checked or not in jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);

How can checked checkbox in jQuery?

There are two methods by which you can dynamically check the currently selected checkbox by changing the checked property of the input type. Method 1: Using the prop method: The input can be accessed and its property can be set by using the prop method.


1 Answers

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.

like image 145
Xian Avatar answered Sep 20 '22 21:09

Xian