Reputation: 6625
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
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
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