HTML CODE:
<form id="myform">
<input type='checkbox' name='foo[]' value='1'>
<input type='checkbox' name='foo[]' checked='true' value='2' >
<input type='checkbox' name='foo[]' value='3' >
<input type='checkbox' name='foo[]' checked='true' value='4' >
</form>
JS CODE:
$('input[name=foo]:checked').each(function(i,el){
if(clusterVal == 'ALL')
{
/* what do I have to do here? */
}
array.push($(el).val());
});
how to check/uncheck checkbox by using value in query
HTML CODE:
<form id="myform">
<input type='checkbox' name='foo[]' value='1'>
<input type='checkbox' name='foo[]' checked='true' value='2' >
<input type='checkbox' name='foo[]' value='3' >
<input type='checkbox' name='foo[]' checked='true' value='4' >
</form>
JS CODE:
$('input[name=foo]:checked').each(function(i,el){
if(clusterVal == 'ALL')
{
/* what do I have to do here? */
}
array.push($(el).val());
});
how to check/uncheck checkbox by using value in query
Share Improve this question edited Aug 3, 2012 at 11:17 Zeta 106k13 gold badges204 silver badges246 bronze badges asked Aug 3, 2012 at 11:14 Vishakha SehgalVishakha Sehgal 331 silver badge5 bronze badges 1- Did you google it ?! google..lb/… – amd Commented Aug 3, 2012 at 11:16
5 Answers
Reset to default 3As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
try this ..but this to just demo how to do check and uncheck
DEMO
$(function(){
var el=$('input:checkbox[name="foo[]:checked"]');
el.each(function()
{
$(this).prop('checked', true);
});
});
Set the checked attribute of the checkbox element to true or false, i.e.
el.checked = false;
If you want to do it with jquery, use the attr function an the checked attibute as well
Hans is right, although But as Anthony pointed out to me, el
will likely be a jQuery object (.each
method returns jQuery objects in this case. as Anthony pointed out, This isn't always the case.)el
won't always be a pure dom object. It can sometimes be a jQuery object, so the checked
property isn't necessarily available. A couple of ways to deal with those cases:
$(el).get(0).checked = false;
$(el).removeAttr('checked');//or $(el).attr('checked',false);
$(el).get(0).checked = true;
$(el).attr('checked','checked');
Credit to Anthony for pointing out my thick-headedness on $.each
and .each
's behaviour :)
Use the prop or the attr to do this. Something like this
$(el).attr("checked", "checked");
or
$(el).prop("checked", true);
Jquery API Prop()
You can check or uncheck element following
$(element).prop('checked',true); // check
$(element).prop('checked',false); // uncheck