我有一个选择控件,在一个javascript变量,我有一个文本字符串。

使用jQuery,我想设置选择控件的选定元素为我有文本描述的项目(而不是值,这是我没有的)。

我知道用值来设置它很简单。如。

$("#my-select").val(myVal);

但我有点难住了,通过文本描述。我想一定有办法从文本描述中得到价值,但我的大脑在周五下午太忙了,无法解决这个问题。


当前回答

试试这个…选择myText文本选项

$("#my-Select option[text=" + myText +"]").prop("selected", true);

其他回答

这只是题外话。没有设置我选择的值。我搜遍了整个网络。实际上,我必须从web服务回调后选择一个值,因为我从它得到数据。

$("#SelectMonth option[value=" + DataFromWebService + "]").attr('selected', 'selected'); 
$("#SelectMonth").selectmenu('refresh', true);

所以刷新选择器是我唯一缺少的东西。

看看jquery selectedbox插件

selectOptions(value[, clear]): 

按值选择选项,使用字符串作为参数$("#myselect2")。selectOptions("Value 1");,或者正则表达式$("#myselect2").selectOptions(/^val/i);。

你也可以清除已经选择的选项:$("#myselect2")。selectOptions("Value 2", true);

这里有一个很简单的方法。请使用它

$("#free").val("y").change();

Try

[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )

[... mySelect选项)。前言(o=> o.选择= o.文本=“文本C”); 选择< id =“mySelect > <option value=“A”>短信A</option> <option value=“B”>短信B</option> <option value=“C”>短信</option> 选择< - >

我发现通过使用attr,你最终会选择多个选项,当你不想-解决方案是使用prop:

$(“#myDropDown option:text=“+ myText +”)。道具(selected”、“selected”);