Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected"). text(); alert ($var);
You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.
Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).
We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.
This could help:
$('#test').find('option[text="B"]').val();
Demo fiddle
This would give you the option with text B
and not the ones which has text that contains B
. Hope this helps
For recent versions of jQuery the above does not work. As commented by Quandary below, this is what works for jQuery 1.9.1:
$('#test option').filter(function () { return $(this).html() == "B"; }).val();
Updated fiddle
You can use the :contains()
selector to select elements that contain specific text.
For example:
$('#mySelect option:contains(abc)')
To check whether a given <select>
element has such an option, use the .has()
method:
if (mySelect.has('option:contains(abc)').length)
To find all <select>
s that contain such an option, use the :has()
selector:
$('select:has(option:contains(abc))')
None of the previous suggestions worked for me in jQuery 1.7.2 because I'm trying to set the selected index of the list based on the value from a textbox, and some text values are contained in multiple options. I ended up using the following:
$('#mySelect option:contains(' + value + ')').each(function(){
if ($(this).text() == value) {
$(this).attr('selected', 'selected');
return false;
}
return true;
});
I faced the same issue below is the working code :
$("#test option").filter(function() {
return $(this).text() =='Ford';
}).prop("selected", true);
Demo : http://jsfiddle.net/YRBrp/83/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With