El Ronnoco
El Ronnoco

Reputation: 11922

jQuery selector problem

<input type="radio" id="rad1" name="group" value="one">First Option</input><br>
<input type="radio" id="rad2" name="group" value="two">Second Option</input><br>
<input type="radio" id="rad3" name="group" value="three">Third Option</input><br>

<br>

<input type="radio" id="rad7" name="group2" value="one">First Option</input><br>
<input type="radio" id="rad8" name="group2" value="two">Second Option</input><br>
<input type="radio" id="rad9" name="group2" value="three">Third Option</input><br>

The following statements are true

$('[value="one"]').length == 2

$('[name="group2"]').length == 3

So how come..

$('[value="one"]',$('[name="group2"]')).length == 0

?

I would have thought that this should effectively look within all elements with name==group2 for elements with value=="one" ie 1. Why is this not the case?

Upvotes: 0

Views: 216

Answers (5)

BoltClock
BoltClock

Reputation: 723618

This selector, using the second argument for scope/context:

$('[value="one"]', $('[name="group2"]'))

Attempts to find elements with [value="one"] that descend from elements with [name="group2"]. That means you end up looking down at least two levels of different elements in the DOM.

In your case, your radio buttons have both attributes, so you want to attach both attribute selectors instead (I add input just to save jQuery some work):

$('input[name="group2"][value="one"]')

Upvotes: 4

versute
versute

Reputation: 1

try the length of $('[value="one"], [name="group2"]')

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816422

I think what you want is:

$('[name="group2"][value="one"]')

This selects elements that have a name attribute with value group2 and value attribute with value one.

$(selector, element) is something different. It will find all descendants of element which match selector. See the documentation.

Upvotes: 2

user113716
user113716

Reputation: 322492

You want this instead to find value one from group2:

$('input[name="group2"][value="one"]').length

This is called the multiple-attribute-selector(docs).

Notice that I also added an input tag selector. This is so every element on the page doesn't need to be analyzed.

Upvotes: 1

jAndy
jAndy

Reputation: 236022

$('input:[value="one"], input:[name="group2"]').length === 5

You have to use one string, comma separated. BTW it's bad practice to write a selector like [anything=foobar]. That is an implicit usage of the universal selector(*) which would query all elements in your markup.

This would query both selectors and add the results together in a wrapped set. If you want query for nodes which own both attributes, wire things up like:

$('input:[value="one"][name="group2"]').length === 1

Upvotes: 1

Related Questions