Reputation: 31
I have html with a <select>
tag and <option>
tags. I get a certain option / value in this way:
$(targetElement).children("option[text=" + Text + "]").val();
where targetElement
is my <select>
element and Text
is the text of the option I want to find.
This works fine when there are multiple options in the select
(on jsFiddle), but when there is only one option, I get undefined
(on jsFiddle)!
Can anyone tell me why it doesn't work when there is only one option, and how I can fix it?
Upvotes: 3
Views: 109
Reputation: 8706
Try this:
$(function(){
var lastOptionValue = $('select > option:last').val();
alert(lastOptionValue);
});
You can try here.
EDIT: Sorry, I was unattentive...
This is your correct example:
$(function(){
text = 'Foo';
var $last = $('select>option').filter(function(){
return $(this).text() == text;
}).last();
if ($last.length > 0){
alert($last.val());
}
});
You can add more functionality in filter()
anonymous function. For example RegExp or something else what you need.
Upvotes: 2
Reputation: 7863
You could also make use of the .filter()
method:
var txt = "Bar";
var x = $('select').children().filter(function() {
return $(this).text() == txt;
}).val();
console.log(x);
This will return the one value with 'Bar' as it's text.
Upvotes: 2
Reputation: 14409
[name=value]
syntax is meant to check the attributes of an element. For example, it would be used to match FooInAttribute but not FooInContents below.
<option value="42" text="FooInAttribute">FooInContents</option>
I can't tell you why it works when there are multiple <option>
tags available, but :contains
works in both scenarios. Try this instead, but as InviS notes, this assumes that no option in the list contains the full text of another (i.e., if you have an option called 'Burger', you must not have another 'Burger and Fries'):
$(targetElement).children("option:contains('" + text + "')").val();
Upvotes: 2