jQuery-通过文本描述设置选择控件的选择值

JavaScript

宝儿卡卡西理查德

2020-03-12

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

我想使用jQuery将select控件的selected元素设置为具有我的文本描述的项目(而不是我没有的值)。

我知道按值设置它是微不足道的。例如

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

但是我对通过文本描述进行操作感到有些困惑。我想一定有办法从文本描述中获取价值,但是星期五下午我的大脑太忙了,无法计算出来。

第1107篇《jQuery-通过文本描述设置选择控件的选择值》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

11个回答
小卤蛋JinJin 2020.03.12

Get the children of the select box; loop through them; when you have found the one you want, set it as the selected option; return false to stop looping.

前端逆天前端 2020.03.12

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

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

我发现通过使用attr您最终会在不想使用时选择多个选项-解决方案是使用prop

$("#myDropDown option:text=" + myText +"").prop("selected", "selected");

小宇宙猴子 2020.03.12

看看jquery selectedbox插件

selectOptions(value[, clear]): 

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

您还可以清除已选择的选项: $("#myselect2").selectOptions("Value 2", true);

前端LEYLEY 2020.03.12

这是非常简单的方法。请使用它

$("#free").val("y").change();
小胖Green梅 2020.03.12

1.7+的最简单方法是:

$("#myDropDown option:text=" + myText +"").attr("selected", "selected"); 

1.9+

$("#myDropDown option:text=" + myText +"").prop("selected", "selected"); 

经过测试和工作。

Green前端 2020.03.12

我知道这是一篇旧文章,但是我无法使用jQuery 1.10.3和上述解决方案通过文本进行选择。我最终使用了以下代码(spoulson解决方案的变体):

      var textToSelect = "Hello World";

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

希望它可以帮助某人。

A逆天猿 2020.03.12

试试这个...选择带有文本myText的选项

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

我采用这种方式(jQuery 1.9.1)

$("#my-select").val("Dutch").change();

注意:不要忘了change(),因此我不得不搜索很长时间:)

古一小胖 2020.03.12

我尚未对此进行测试,但这可能对您有用。

$("select#my-select option")
   .each(function() { this.selected = (this.text == myVal); });
Near西里泡芙 2020.03.12

为了避免所有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;
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android