我有一个选择控件,在一个javascript变量,我有一个文本字符串。
使用jQuery,我想设置选择控件的选定元素为我有文本描述的项目(而不是值,这是我没有的)。
我知道用值来设置它很简单。如。
$("#my-select").val(myVal);
但我有点难住了,通过文本描述。我想一定有办法从文本描述中得到价值,但我的大脑在周五下午太忙了,无法解决这个问题。
我有一个选择控件,在一个javascript变量,我有一个文本字符串。
使用jQuery,我想设置选择控件的选定元素为我有文本描述的项目(而不是值,这是我没有的)。
我知道用值来设置它很简单。如。
$("#my-select").val(myVal);
但我有点难住了,通过文本描述。我想一定有办法从文本描述中得到价值,但我的大脑在周五下午太忙了,无法解决这个问题。
当前回答
如果您试图将select与ID绑定,那么下面的代码对我来说是有效的。
<select name="0product_id[]" class="groupSelect" id="groupsel_0" onchange="productbuilder.update(this.value,0);">
<option value="0" class="notag" id="id0_0">--Select--</option>
<option class="notag" value="338" id="id0_338" >Dual Promoter Puromycin Expression Plasmid - pSF-CMV-PGK-Puro > £114.00</option>
<option class="notag" value="282" id="id0_282" >EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro > £114.00</option>
<option class="notag" value="265" id="id0_265" >FMDV IRES Puromycin Expression Plasmid - pSF-CMV-FMDV-Puro > £114.00</option>
<option class="notag" value="101" id="id0_101" >Puromycin Selection Plasmid - pSF-CMV-Ub-Puro AscI > £114.00</option>
<option class="notag" value="105" id="id0_105" >Puromycin Selection SV40 Ori Plasmid - pSF-CMV-Ub-Puro-SV40 Ori SbfI > £114.00</option></select>
这是js代码
$( document ).ready(function() {
var text = "EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro > £114.00";
alert(text);
$("#groupsel_0 option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text;
}).prop('selected', true);
});
其他回答
$("#myselect option:contains('YourTextHere')").val();
将返回包含文本描述的第一个选项的值。测试了这一点,并工作。
这只是题外话。没有设置我选择的值。我搜遍了整个网络。实际上,我必须从web服务回调后选择一个值,因为我从它得到数据。
$("#SelectMonth option[value=" + DataFromWebService + "]").attr('selected', 'selected');
$("#SelectMonth").selectmenu('refresh', true);
所以刷新选择器是我唯一缺少的东西。
我还没有测试过,但这可能对你有用。
$("select#my-select option")
.each(function() { this.selected = (this.text == myVal); });
为了避免所有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;
}
jQuery 1.9.1 (jQuery 1.9.1)
$("#my-select").val("Dutch").change();
注意:不要忘记更改(),我不得不搜索很长时间,因为那:)