dharga
dharga

Reputation: 2217

JQuery Selector to select dropdown by value

I have a set of Yes/No dropdowns and I'd like to select all select elements with a value of Yes.

<select name="foo1">
  <option value="yes">Yes</option>
  <option value="no">No</option>
</select>
<select name="foo2">
  <option value="yes">Yes</option>
  <option value="no">No</option>
</select>
<select name="foo3">
  <option value="yes">Yes</option>
  <option value="no">No</option>
</select>

I'd like a JQuery selector that returns a subset of select nodes which are currently in a state of Yes. I realize I can do a simple call to filter(), but I would much rather do it all in a selector.

$('#myform select').filter(function(k,v){return v.value == 'yes';})

Thanks in advance.

Upvotes: 0

Views: 1047

Answers (4)

wirey00
wirey00

Reputation: 33661

it would be

$('#form select:has(option[value=yes]:selected)')

It will get all select that has option:selected with a value=yes

FIDDLE

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 219920

If you want it to be efficient, you should stick to filter, but you can create a custom filter that you can use directly in your selector:

$.expr[':'].value = $.expr.createPseudo(function (value) {
    return function (el) {
        return el.value == value;
    };
});

Use it as follows:

$('select:value(yes)');

Here's the fiddle: http://jsfiddle.net/Eb3hp/

Upvotes: 1

mVChr
mVChr

Reputation: 50177

$('#myform select option[value="yes"]:selected').parent()

See demo

Upvotes: 2

James Coyle
James Coyle

Reputation: 10398

$('#myform select[value=yes]');

Upvotes: 0

Related Questions