本文翻译自:jQuery - setting the selected value of a select control via its text description
I have a select control, and in a javascript variable I have a text string. 我有一个选择控件,在一个javascript变量中我有一个文本字符串。
Using jQuery I want to set the selected element of the select control to be the item with the text description I have (as opposed to the value, which I don't have). 使用jQuery我想将select控件的selected元素设置为具有我所拥有的文本描述的项目(而不是我没有的值)。
I know setting it by value is pretty trivial. 我知道按值设置它是非常微不足道的。 eg 例如
$("#my-select").val(myVal);
But I'm a bit stumped on doing it via the text description. 但是通过文字描述我有点难过。 I guess there must be a way of getting the value out from the text description, but my brain is too Friday afternoon-ed to be able to work it out. 我想必须有一种从文本描述中获取价值的方法,但是我的大脑在星期五下午也可以解决它。
#1楼
参考:https://stackoom.com/question/252q/jQuery-通过文本描述设置选择控件的选定值
#2楼
Easiest way with 1.7+ is: 1.7+的最简单方法是:
$("#myDropDown option:text=" + myText +"").attr("selected", "selected");
1.9+ 1.9+
$("#myDropDown option:text=" + myText +"").prop("selected", "selected");
Tested and works. 经过测试和工作。
#3楼
To avoid all jQuery version complications, I honestly recommend using one of these really simple javascript functions... 为了避免所有jQuery版本的复杂性,我老实说建议使用其中一个非常简单的javascript函数...
function setSelectByValue(eID,val)
{ //Loop through sequentially//
var ele=document.getElementById(eID);
for(var ii=0; ii<ele.length; ii++)
if(ele.options[ii].value==val) { //Found!
ele.options[ii].selected=true;
return true;
}
return false;
}
function setSelectByText(eID,text)
{ //Loop through sequentially//
var ele=document.getElementById(eID);
for(var ii=0; ii<ele.length; ii++)
if(ele.options[ii].text==text) { //Found!
ele.options[ii].selected=true;
return true;
}
return false;
}
#4楼
Just on a side note. 只是旁注。 My selected value was not being set. 我的选定值未设置。 And i had search all over the net. 我在网上搜索过。 Actually i had to select a value after a call back from a web service, because i was getting data from it. 实际上我必须在从Web服务回调后选择一个值,因为我从中获取数据。
$("#SelectMonth option[value=" + DataFromWebService + "]").attr('selected', 'selected');
$("#SelectMonth").selectmenu('refresh', true);
So the refresh of the selector was was the only thing that i was missing. 所以选择器的刷新是我唯一缺少的东西。
#5楼
我发现通过使用attr
你最终会在你不想要的时候选择多个选项 - 解决方案是使用prop
:
$("#myDropDown option:text=" + myText +"").prop("selected", "selected");
#6楼
I know this is an old post, but I couldn't get it to select by text using jQuery 1.10.3 and the solutions above. 我知道这是一篇旧帖子,但我无法通过使用jQuery 1.10.3及上述解决方案的文本进行选择。 I ended up using the following code (variation of spoulson's solution): 我最终使用了以下代码(spoulson解决方案的变体):
var textToSelect = "Hello World";
$("#myDropDown option").each(function (a, b) {
if ($(this).html() == textToSelect ) $(this).attr("selected", "selected");
});
Hope it helps someone. 希望它可以帮助某人。