gremo
gremo

Reputation: 48909

jQuery select elements when attribute is contained in attribute list?

Better explain with an example (i'm very new to jQuery, sorry in advance):

// Selector for checkboxes not checked
var checkboxes = "input:checkbox:not(:checked)";

// Selector for labels relative to checkboxes not checked
var labels = "label[for=" + $(checkboxes).attr("id") + "]";

$(checkboxes + ", " + labels]).FadeTo("slow", 0.45);

This works for checkboxes but nor for labels (strangely, only one label gets selected).

Question are: how can i select "attached" labels? And, how .attr("name") actually works when more than one element is selected (returns an array, a concatenated list, or... what?).

Upvotes: 0

Views: 189

Answers (3)

usoban
usoban

Reputation: 5478

// Selector for checkboxes not checked
var checkboxes = $('input:checkbox:not(:checked)'), 
    selector = [];

checkboxes.each(function(){
  selector.push('[for="' + $(this).attr('id') + '"]');
});

// Selector for labels relative to checkboxes not checked
var labels = $('label:' + selector.join());

I guess that should be sufficient.

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 77986

Try this:

$('input:checkbox:not(:checked)').each(function(){
    $('label[for=' + $(this).attr('id') + ']').add(this).fadeTo('slow',0.45);
});

Upvotes: 1

BoltClock
BoltClock

Reputation: 723759

(strangely, only one label gets selected)

And, how .attr("name") actually works when more than one element is selected (returns an array, a concatenated list, or... what?).

Calling .attr() on a set of elements only returns the attribute value for the first element. So in your case, the label for the first checkbox is selected.

You can always create a bunch of selector strings dynamically by looping, but that's not very efficient. If your labels and checkboxes are in a predictable HTML structure you can use that to your advantage instead, with jQuery's traversing methods.

Upvotes: 0

Related Questions