Chapsterj
Chapsterj

Reputation: 6625

how to get select option based on value

How would I get a select option based on a value of that option.

for example:

<select>
  <option>option1</option>
  <option>option2</option>
  <option>option3</option>
</select>

I want to find option2 based on the value.

var temp = "option2"; 
$(select).get(temp);

so i'm using get() as an example of what I want to do I know there isn't a get for that but I want it to return option2 as a jquery object.

Upvotes: 1

Views: 254

Answers (3)

Matthew Blancarte
Matthew Blancarte

Reputation: 8301

Edit per good point made by @Rocket::

Try this if using values:

var val;

$( 'select' ).change(function(){
  val = $( 'option:selected', this ).val();
});

Try this if using the inner text:

var text;

$( 'select' ).change(function(){
  text = $( 'option:selected', this ).text();
});

Try this if grabbing the element:

var elem;

$( 'select' ).change(function(){
  elem = $( 'option:selected', this );
});

Upvotes: 1

Tats_innit
Tats_innit

Reputation: 34107

Try this: http://jsfiddle.net/WEWcc/ or like Rocket mentioned without value attribute try this: http://jsfiddle.net/cbyTf/

Could write a custom filter-ish function. :)

code

var temp = "option2";
$(document).ready(function() {

        var filter = temp;
        $('option').each(function() {
            if ($(this).val() == filter) {
                alert($(this).val());
            } else {

            }
            $('select').val(filter);
        })

})​

without value attribute

var temp = "option2";
$(document).ready(function() {

        var filter = temp;
        $('option').each(function() {
            if ($(this).html() == filter) {
                alert($(this).html());
            } else {

            }

        })
   $('select').val(filter);
})​

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227240

You want the :contains selector.

$('option:contains("option2")', 'select')

Upvotes: 5

Related Questions