我想知道如何使用jquery在页面上的所有选择标签中选择第一个选项。
尝试了这个:
$('select option:nth(0)').attr("selected", "selected");
但是没用
我想知道如何使用jquery在页面上的所有选择标签中选择第一个选项。
尝试了这个:
$('select option:nth(0)').attr("selected", "selected");
但是没用
Answers:
试试看...
$('select option:first-child').attr("selected", "selected");
另一个选择是这样,但是它一次仅适用于一个下拉列表,如下所示:
var myDDL = $('myID');
myDDL[0].selectedIndex = 0;
看一下这篇关于如何基于价值进行设置的帖子,它很有趣,但是对于这个特定问题没有帮助:
.prop()方法访问属性。因此,您可以使用$("select").prop("selectedIndex",0);一种快速的方法在所有下拉菜单中选择第一个选项。
$('select').trigger('change');以防万一。谢谢!
var myDDL = $('myID')应该在选择器中具有哈希成为var myDDL = $('#myID')
$('select option').first().prop('selected',true);
Ana替代RSolgberg的解决方案,'onchange'如果存在,则触发该事件:
$("#target").val($("#target option:first").val());
我之所以回答是因为先前的答案已停止使用最新版本的jQuery。我不知道它什么时候停止工作,但是文档说.prop()自jQuery 1.6以来就是获取/设置属性的首选方法。
这是我如何使其工作(使用jQuery 3.2.1):
$('select option:nth-child(1)').prop("selected", true);
我正在使用基因敲除js,并且上面的代码没有触发变更绑定,所以我在最后添加了.change()。
这是我需要的解决方案:
$('select option:nth-child(1)').prop("selected", true).change();
请参阅以下文档中的.prop()注释:http ://api.jquery.com/prop/
如果要检查所选选项的文本,而不管其第一个子项。
var a = $("#select_id option:selected").text();
alert(a); //check if the value is correct.
if(a == "value") {-- execute code --}
$('#myID option:selected').text('NEW STRING');
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);