tags:

views:

65

answers:

4

I have this code, which works fine:

if ( $('table#attribute_Size input.quantitycheckbox:checked').length == 0 )
    $('table#attribute_Size input.quantitycheckbox:first').attr({ checked: true });

As you can see though, it's pretty long and most of the selector is repeated. Is there a neat was to shorten it? I tried this but it doesn't work (I assume it's looking at nested elements instead of the current selector).

var $sizeRadios = $('table#attribute_Size input.quantitycheckbox');
if ( $(':checked', $sizeRadios).length == 0 )
    $(':first', $sizeRadios).attr({ checked: true });
A: 

You can make it a little bit shorter by removing the "table" at the beginning of each selector. It is 100% unnecessary and actually slows down jQuery. You could also cache the table jQuery object like so:

var $table = $('#attribute_Size');
if ($('input.quantitycheckbox:checked', $table).length == 0 )
    $('input.quantitycheckbox:first', $table).attr('checked', true);
David Radcliffe
+2  A: 

You could try this... it's a little shorter. I haven't tested but should work.

var $sizeRadios = $('#attribute_Size input.quantitycheckbox');
if ( !$sizeRadios.is(":checked") )
    $sizeRadios.eq(0).attr("checked", true);
Lindsay
Yup, didn't know about the `is` function. I corrected the if clause - it should only check the first button if none are checked - and removed "table" from the selector as per David Radcliffe's suggestion.
DisgruntledGoat
It might make the code a little longer to include the table but it will also make it perform a little better. It's a trade-off, but personally I'd leave table in.
Lindsay
One other thing... checking a negative condition with selectors is sometimes difficult because there can be multiple items returned. If the first one happens not to be a match then you'll get a false positive if any of the othser are.So for the negative condition you probably would be safer doing this:if ($sizeRadios.filter(":checked").length == 0).filter removes any nodes from the return set that meet the condition.
Lindsay
A: 

You can also write:

var $table = $('#attribute_Size');
if (!$table.find('input.quantitycheckbox').is(':checked'))
  $table.find('input.quantitycheckbox:first').attr('checked', true);

Not really "better" or anything, just a different style.

[edit] oh I like @Lindsay's better.

Pointy
A: 

One select query:

$('#attribute_Size:not(:has(input.quantitycheckbox:checked)) input.quantitycheckbox:first').attr({ checked: true });
David Morton