Easiest “check all” ever with jQuery made even more … easy
I was reading some tweets and I got to this post, which can be improved.
First the html. Don’t use divs for layout purposes.
<fieldset> // these will be affected by check all <div> <input id="checkall" type="checkbox" /> Check all</div> <div> <input type="checkbox" /> Checkbox</div> <div> <input type="checkbox" /> Checkbox</div> <div> <input type="checkbox" /> Checkbox</div> </fieldset> <fieldset> // these won't be affected by check all; different fieldset <div> <input type="checkbox" /> Checkbox</div> <div> <input type="checkbox" /> Checkbox</div> <div> <input type="checkbox" /> Checkbox</div> </fieldset>
The original post divs are nonsense in terms of usability and semantics. Loose them as the original author just needed some BR tags.
<fieldset> <input id="checkall" type="checkbox" /> Check all <input type="checkbox" /> Checkbox <input type="checkbox" /> Checkbox <input type="checkbox" /> Checkbox </fieldset> <fieldset> // these won't be affected by check all; different fieldset <input type="checkbox" /> Checkbox <input type="checkbox" /> Checkbox <input type="checkbox" /> Checkbox </fieldset>
This is the original javascript:
$(function () { // this line makes sure this code runs on page load
$('#checkall').click(function () {
$checkall = $(this); OK
$close = $checkall.parents('fieldset:eq(0)').find('input'); // this is called $close but it should be $elements or something
$checkall.attr('checked') !== true ? $close.removeAttr('checked') : $close.attr('checked', 'checked'); // see my version down
});
});
The javascript can be shortened and I preffer using native functions like is(), pseudoselectors like :checked, and boolean values when accepted instead of strings.
$('#checkall').click( function () {
var all= $(this).siblings();
$(this).is(':checked') ? all.attr('checked', true) : all.attr('checked', false);
});
About this entry
You’re currently reading “Easiest “check all” ever with jQuery made even more … easy,” an entry on Elzo Valugi
- Published:
- 8.17.09 / 12pm
- Category:
- Javascript, jQuery
No comments
Jump to comment form | comments rss [?] | trackback uri [?]