Kevin Lee
Kevin Lee

Reputation: 1089

How do i chain these two jquery statements into one?

Ok, I want to chain these statements into one, but i don't know how it works yet..

I have lots of input in my html file, and then if i click a link, it will just check that link and make other input check boxes uncheck.. Here's my current code for that:

$('.category').click(function() {
   $('input[name=category]').attr('checked', false);
   $(this).parent().find('input').attr('checked', true);
}

I think this might be slow because the second statement will go to its parent and then find the input then checked it.. It might be possible to combine these into one and make it faster?

Upvotes: 0

Views: 216

Answers (3)

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14747

Seeing that call to .parent().find() on your chain makes me think that you're actually looking for a sibling? You may get better mileage by using the .siblings() function.

With that in mind, you may want to phrase your code like this:

$('.category').click(function(){
    $('[name="category"]').attr('checked',true);
    $(this).siblings('input:checkbox').attr('checked',true);
});

It's difficult to construct a proper chain for your particular DOM without first seeing the code, but the code above should be OK. Doesn't look heavy at all.

Upvotes: 3

Chris Marais
Chris Marais

Reputation: 411

You can add extra filtering into your .find() to only look for checkboxes

$(this).parent().find('input[type="checkbox"]').attr('checked', true);

Upvotes: 2

neurino
neurino

Reputation: 12395

Make finds just once...

var $category = $('input[name=category]');
var $inputs = $('your_parent_selector');
$('.category').click(function() {
   $category.attr('checked', false);
   $inputs.attr('checked', true);
}

Upvotes: -1

Related Questions