使用JQUERY通过文本选择选项获取值

Select option get value by text using JQUERY

本文关键字:选项 获取 选择 文本 JQUERY 使用      更新时间:2023-09-26

我有html选择(下拉)与许多填充的选项。此外,我有许多名称与按钮旁边的表。我需要,当你按下按钮旁边的任何名称,然后该名称将在选择框中选择(下拉)。选项值为id,选项文本为名称。例子:


!NamesList!v!   <- select box
John  !Button!
Tom   !Button!
Laura !Button!    

我已经尝试使用:

var name = "John";
$("#cmbOperator option[value='" + name + "']").attr('selected', 'selected'); 

但它不起作用。如果我改变var名称为id(这是值),然后工作。但是我如何从文本中获取选项的值呢?

$("select option:contains(text)").attr('selected', true);

这里是JSFiddle

http://jsfiddle.net/u1c21mq6/1/

如果你的HTML :

<select id="cmbOperator">
    <option value="Jane">Jane</option>
    <option value="John">John</option>
</select>
使用

:

$("#cmbOperator option[value='" + name + "']").attr('selected', 'selected');

  • 根据value属性进行选择。

$("#cmbOperator option:contains('" + name + "')").attr('selected', 'selected');

  • 根据文本内容进行选择。


如果你的HTML是:

<select id="cmbOperator">
    <option>Jane</option>
    <option>John</option>
</select>
使用

:

$("#cmbOperator option:contains('" + name + "')").attr('selected', 'selected');