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:36

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;
});
查看更多
十年一品温如言
3楼-- · 2019-01-01 11:36

This work for me

$('#mySelect option:contains(' + value + ')').attr('selected', 'selected');
查看更多
大哥的爱人
4楼-- · 2019-01-01 11:36

Either you iterate through the options, or put the same text inside another attribute of the option and select with that.

查看更多
登录 后发表回答