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.

// these will be affected by check all
Check all
Checkbox
Checkbox
Checkbox
// these won't be affected by check all; different fieldset
Checkbox
Checkbox
Checkbox

The original post divs are nonsense in terms of usability and semantics. Loose them as the original author just needed some BR tags.

Check all Checkbox Checkbox Checkbox
// these won't be affected by check all; different fieldset Checkbox Checkbox Checkbox

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