javascript - Setting "checked" for a checkbox with jQuery? -


i'd tick checkbox using jquery:

$(".mycheckbox").checked(true); 

or

$(".mycheckbox").selected(true); 

does such thing exist?

jquery 1.6+

use new .prop() method:

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

jquery 1.5.x , below

the .prop() method not available, need use .attr().

$('.mycheckbox').attr('checked', true); $('.mycheckbox').attr('checked', false); 

note the approach used jquery's unit tests prior version 1.6 , preferable using

$('.mycheckbox').removeattr('checked'); 

since latter will, if box checked, change behaviour of call .reset() on form contains - subtle unwelcome behaviour change.

for more context, incomplete discussion of changes handling of checked attribute/property in transition 1.5.x 1.6 can found in version 1.6 release notes , attributes vs. properties section of .prop() documentation.

any version of jquery

if you're working 1 element, can modify htmlinputelement's .checked property:

$('.mycheckbox')[0].checked = true; $('.mycheckbox')[0].checked = false; 

the benefit using .prop() , .attr() methods instead of operate on matched elements.


Comments