![](/img/trans.png)
[英]Using jQuery, how do I get a specific dropdown element (<select></select>) based on the value of the dropdown?
[英]How to select the first element in the dropdown using jquery?
我想知道如何使用jquery在我的页面上的所有选择标签中选择第一个选项。
试过这个:
$('select option:nth(0)').attr("selected", "selected");
但没有奏效
试试这个......
$('select option:first-child').attr("selected", "selected");
另一种选择是这个,但它只能一次用于一个下拉列表,如下所示:
var myDDL = $('myID');
myDDL[0].selectedIndex = 0;
看看这篇关于如何基于价值进行设置的帖子,它有趣但不会帮助您解决这个特定问题:
你的选择器错了,你可能正在寻找
$('select option:nth-child(1)')
这也可以:
$('select option:first-child')
用于RSolgberg的Ana替代解决方案,如果存在,则触发'onchange'
事件:
$("#target").val($("#target option:first").val());
$("#DDLID").val( $("#DDLID option:first-child").val() );
你想要的可能是:
$("select option:first-child")
这段代码是什么
attr("selected", "selected");
正在做的是将“selected”属性设置为“selected”
如果您想要所选的选项,无论它是否是第一个子选项,选择器都是:
$("select").children("[selected]")
我正在回答,因为之前的答案已停止使用最新版本的jQuery。 我不知道它什么时候停止工作,但文档说.prop()是自jQuery 1.6以来获取/设置属性的首选方法。
这就是我如何使用它(使用jQuery 3.2.1):
$('select option:nth-child(1)').prop("selected", true);
我正在使用knockoutjs并且更改绑定没有使用上面的代码触发,所以我将.change()添加到最后。
这就是我的解决方案所需要的:
$('select option:nth-child(1)').prop("selected", true).change();
请参阅此处文档中的.prop()说明: http ://api.jquery.com/prop/
这是一个简单的javascript
解决方案,适用于大多数情况:
document.getElementById("selectId").selectedIndex = "0";
var arr_select_val=[];
$("select").each(function() {
var name=this.name;
arr_select_val[name]=$('select option:first-child').val();
});
// Process the array object
$('.orders_status_summary_div').print(arr_select_val);
如果你想检查所选选项的文本,无论它是第一个孩子。
var a = $("#select_id option:selected").text();
alert(a); //check if the value is correct.
if(a == "value") {-- execute code --}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.