<div id="notifydaydiv" name="notifydaydiv" style="display:none; padding-left:50px">
<input name="notifyday" type="checkbox" value="wed" /> Wednesday <br />
<input name="notifyday" type="checkbox" value="thu" /> Thursday <br />
<span style="color:red; font-size:7pt;">Recommended</span><br />
<input name="notifyday" type="checkbox" value="fri" checked="checked"/> Friday
<div id="day_err"></div>
<script>
[ set which checkbox is checked based on the value attr ]
</script>
</div>
views:
29answers:
3
+1
Q:
How can I set an individual checkbox in a checkbox group to "checked" based on it's value attr ?
+2
A:
$(":checkbox[value='wed']").attr('checked', 'checked');
For more information, see the JQuery API.
Deniz Dogan
2010-06-22 13:36:30
A:
You can find and check it using the attribute-equals selector, like this:
$(":checkbox[value='wed']").attr('checked', true);
You can also use name
in there if needed, like this:
$(":checkbox[name='notifyday'][value='wed']").attr('checked', true);
Nick Craver
2010-06-22 13:36:35
Beat you by five very solid seconds...!
Deniz Dogan
2010-06-22 13:37:36
@Deniz - Almost ;) You should use `true` or `false` here, that's the way it's normalized, e.g. `.att('checked') === true` :)
Nick Craver
2010-06-22 13:39:19
@Nick: Did not know that. Where can I read about it?
Deniz Dogan
2010-06-22 13:40:27
@Deniz - Not sure actually, something you learn along the way I guess. No specifics in the [docs](http://api.jquery.com/attr/), just this: **Cross-browser consistency:** Some attributes have inconsistent naming from browser to browser. Furthermore, the values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The `.attr()` method reduces such inconsistencies.
Nick Craver
2010-06-22 13:54:34
I like the use of name here. Seems more clear. So Deniz you're saying it should look like this: $(":checkbox[name='notifyday'][value='wed']").attr('checked') === true ??
isuelt
2010-06-22 13:58:56
@isuelt - `.attr('checked')` *gets* the value, it would be `true` if checked, `false` if not, but you can also use that to *set* the value, e.g. `.attr('checked', true)` to check or `.attr('checked', false)` to uncheck.
Nick Craver
2010-06-22 14:02:41
Awesome. Thanks!
isuelt
2010-06-22 14:09:49
A:
$(document).ready(function(){
$(":checkbox[value='wed']").attr('checked', 'checked');
});
Make sure that the page is loaded before you try and check the checkbox.
runxc1 Bret Ferrier
2010-06-22 13:40:56