How to select an option by its text?

2019-01-01 10:36发布

I need to check if a <select> has an option whose text is equal to a specific value.

For example, if there's an <option value="123">abc</option>, I would be looking for "abc".

Is there a selector to do this?

Im looking for something similar to $('#select option[value="123"]'); but for the text.

标签: jquery
15条回答
裙下三千臣
2楼-- · 2019-01-01 11:30

I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.

$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());

another way of writing it in a more readable fasion:

var valofText = $("#my-Select" + " option").filter(function() {
    return this.text == myText
}).val();
$(ElementID).val(valofText);

Pseudocode:

$("#my-Select").val( getValOfText( myText ) );
查看更多
残风、尘缘若梦
3楼-- · 2019-01-01 11:31

This works for me

var options = $(dropdown).find('option');
var targetOption = $(options).filter(
function () { return $(this).html() == value; });

console.log($(targetOption).val());

Thanks for all the posts.

查看更多
闭嘴吧你
4楼-- · 2019-01-01 11:32

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/

查看更多
一个人的天荒地老
5楼-- · 2019-01-01 11:32

This will work in jQuery 1.6 (note colon before the opening bracket), but fails on the newer releases (1.10 at the time).

$('#mySelect option:[text=abc]")
查看更多
孤独总比滥情好
6楼-- · 2019-01-01 11:35

This worked for me: $("#test").find("option:contains('abc')");

查看更多
余欢
7楼-- · 2019-01-01 11:36

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))')
查看更多
登录 后发表回答