views:

36

answers:

2

This:

$('input.people').attr('checked', false).filter('[name=toddS]').attr('checked', true);

will select a checkbox with the class of people and the name toddS while unchecking all of the other boxes.

How do I add another name to the filter? I've tried several different combinations and nothing works. This is what I have:

$('input.people').attr('checked', false).filter('[name=toddS], [name=gwenD]').attr('checked', true);
A: 

You could use a function there to select the ones you want only.

$('input.people')
   .removeAttr('checked')
   .filter(function() {
       return ($(this).attr('name') === 'toddS' || $(this).attr('name') === 'gwenD');
    })
    .attr('checked', 'checked');

I also used removeAttr() instead of setting it to false. I haven't checked what jQuery does by setting it to false, but from a HTML perspective, being unchecked should mean the absence of that attribute.

alex
+1  A: 

You can pass a function into .attr(), like this:

$('input.people').attr('checked', function() {
  return this.name == 'toddS' || this.name == 'gwenD';
});

If you need to add more later, you can use something that works for more values, for instance $.inArray(), like this:

$('input.people').attr('checked', function() {
  return $.inArray(this.name, ['toddS', 'gwenD']) != -1;
});
Nick Craver
Yup; intentions are much clearer with this alternative.
strager
Thanks, Nick. Now how do I uncheck Todd and Gwen when their position(s) are unchecked?
@sehummel65 - Can you clarify a bit? I'm not understanding the question...you want the reverse, or to uncheck everyone or...?
Nick Craver