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

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

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

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

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


当前回答

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

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

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

其他回答

$("#myselect option:contains('YourTextHere')").val();

将返回包含文本描述的第一个选项的值。测试了这一点,并工作。

这句话很管用:

$("#myDropDown option:contains(myText)").attr('selected', true);

获取选择框的子元素;循环遍历它们;当你找到你想要的选项时,将其设置为所选选项;返回false停止循环。

这只是题外话。没有设置我选择的值。我搜遍了整个网络。实际上,我必须从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);