Wednesday, October 14, 2009

jQuery, checkbox status

I wanted to find the state of a checkbox and hide or show some text using jQuery. The thing that I got stuck on was determining if the checkbox was checked. This is how I ended up doing it:

<script type="text/javascript">
$(document).ready(function() {
$("input[name='cbname']").click( function() {
if ($(this).attr('checked'))
$('#text').hide();
else
$('#text').show();
});
});
</script>
<input type="checkbox" name="cbname"> Hide!
<div id="text">
Disappearing Text
</div>

Simply checking the attribute 'checked' of the checkbox returns its state (in jQuery 1.3.2, at least).

No comments: