Search code examples
jqueryjquery-selectorshtml-select

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?


Solution

  • 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"]');