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

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

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

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

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


当前回答

我知道这是一篇老文章,但是我无法使用jQuery 1.10.3和上面的解决方案来实现文本选择。 我最终使用以下代码(spoulson的解决方案的变化):

      var textToSelect = "Hello World";

      $("#myDropDown option").each(function (a, b) {
            if ($(this).html() == textToSelect ) $(this).attr("selected", "selected");
        });

希望它能帮助到别人。

其他回答

 $("#Test").find("option:contains('two')").each(function(){
     if( $(this).text() == 'two' ) {
        $(this).attr("selected","selected");
     }
 });

if语句与"two"进行精确匹配,"two 3 "将不会被匹配

这里有一个简单的选择。只需设置列表选项,然后将其文本设置为选定值:

$("#ddlScheduleFrequency option").selected(text("Select One..."));

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

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

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

如果您试图将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();

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