juanchito
juanchito

Reputation: 521

Getting options by value from select element in jQuery

I want to access the select option jQuery objects as such:

var $options = $('select').children();
var $someOption = $('[value="some_value"]', $options);
var $anotherOption = $('[value="another_value"]', $options);

but neither $someOption or $anotherOption look like any of the elements in $('select').

I believe I know how to compose the one line selector but since I'm accessing various options, I wanted to use the $options handle for readability and performance instead.

What is wrong with the code and/or rationale?

Upvotes: 4

Views: 129

Answers (2)

Barmar
Barmar

Reputation: 780655

In order to use the context parameter, don't call .children().

var $select = $('select');
var $someOption = $('[value="some_value"]', $select);
var $anotherOption = $('[value="another_value"]', $select);

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 219910

You have to use jQuery's filter method:

var $options = $('select').children();
var $someOption = $options.filter('[value="some_value"]');
var $anotherOption = $options.filter('[value="another_value"]');

Upvotes: 5

Related Questions