【发布时间】:2010-11-26 13:03:33
【问题描述】:
我想知道如何使用 jquery 在我的页面上的所有选择标签中选择第一个选项。
试过这个:
$('select option:nth(0)').attr("selected", "selected");
但是没用
【问题讨论】:
标签: javascript jquery html
我想知道如何使用 jquery 在我的页面上的所有选择标签中选择第一个选项。
试过这个:
$('select option:nth(0)').attr("selected", "selected");
但是没用
【问题讨论】:
标签: javascript jquery html
这是一个简单的javascript 解决方案,适用于大多数情况:
document.getElementById("selectId").selectedIndex = "0";
【讨论】:
试试这个...
$('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);
我正在回答,因为以前的答案已停止使用最新版本的 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/
【讨论】:
您的选择器错误,您可能正在寻找
$('select option:nth-child(1)')
这也可以:
$('select option:first-child')
【讨论】:
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);
【讨论】:
RSolgberg 的另一种解决方案,如果存在会触发 'onchange' 事件:
$("#target").val($("#target option:first").val());
【讨论】:
$("#DDLID").val( $("#DDLID option:first-child").val() );
【讨论】:
如果您想检查所选选项的文本,无论它是否是第一个孩子。
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');
你想要的大概是:
$("select option:first-child")
这是什么代码
attr("selected", "selected");
正在做的是将“selected”属性设置为“selected”
如果要选中的选项,不管是不是first-child,选择器都是:
$("select").children("[selected]")
【讨论】:
attr 替换为 prop