Javascript jQuery:设置下拉列表的选定值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5810016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:59:53  来源:igfitidea点击:

jQuery: set selected value of dropdown list?

javascriptjquery

提问by simon

What's wrong with this code?

这段代码有什么问题?

jQuery

jQuery

$(document).ready(function() {
    $("#routetype").val('quietest');
)};

HTML

HTML

<select id="routetype" name="routetype">
    <option value="fastest">Fastest</option>
    <option selected="true" value="balanced">Balanced</option>
    <option value="quietest">Quietest</option>
</select>

Fiddle

小提琴

It gives me 'Balanced' as the selected option, not 'Quietest'.

它给了我“平衡”作为选择的选项,而不是“最安静”。

采纳答案by mVChr

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).readyshould end with });not )};Check this link.

您需要在左侧的下拉列表中选择 jQuery 并且您有语法错误,因为$(document).ready应该以});not检查此链接结束)};

回答by mattsven

UPDATED ANSWER:

更新的答案:

Old answer, correct method nowadays is to use jQuery's .prop(). IE, element.prop("selected", true)

旧答案,现在正确的方法是使用 jQuery 的.prop(). IE,element.prop("selected", true)

OLD ANSWER:

旧答案:

Use this instead:

改用这个:

$("#routetype option[value='quietest']").attr("selected", "selected");

Fiddle'd:http://jsfiddle.net/x3UyB/4/

小提琴:http : //jsfiddle.net/x3UyB/4/

回答by Hardik

You can select dropdown option value by name

您可以按名称选择下拉选项值

jQuery("#option_id").find("option:contains('Monday')").each(function()
{
 if( jQuery(this).text() == 'Monday' )
 {
  jQuery(this).attr("selected","selected");
  }
});