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

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

查看更多
妖精总统
3楼-- · 2019-01-01 11:19

As described in this answer, you can easily create your own selector for hasText. This allows you to find the option with $('#test').find('option:hastText("B")').val();

Here's the hasText method I added:

 if( ! $.expr[':']['hasText'] ) {
     $.expr[':']['hasText'] = function( node, index, props ) {
       var retVal = false;
       // Verify single text child node with matching text
       if( node.nodeType == 1 && node.childNodes.length == 1 ) {
         var childNode = node.childNodes[0];
         retVal = childNode.nodeType == 3 && childNode.nodeValue === props[3];
       }
       return retVal;
     };
  }
查看更多
后来的你喜欢了谁
4楼-- · 2019-01-01 11:23

Use following

$('#select option:contains(ABC)').val();
查看更多
何处买醉
5楼-- · 2019-01-01 11:26

For jquery version 1.10.2 below worked for me

  var selectedText="YourMatchText";
    $('#YourDropdownId option').map(function () {
       if ($(this).text() == selectedText) return this;
      }).attr('selected', 'selected');
    });
查看更多
回忆,回不去的记忆
6楼-- · 2019-01-01 11:27

This will also work.

$('#test').find("select option:contains('B')").filter(":selected");

查看更多
墨雨无痕
7楼-- · 2019-01-01 11:30

This is the best method for select text in dropdownlist.

$("#dropdownid option:contains(your selected text)").attr('selected', true);
查看更多
登录 后发表回答