jQuery 使用jQuery设置DropDown的selectedIndex?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10508795/
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
set the selectedIndex of a DropDown using jQuery?
提问by Nick Kahn
i am trying to set the index of an dropdown to 0; if the user is uncheck the checkbox as show in the example but some how its just ignoring...
我正在尝试将下拉列表的索引设置为 0;如果用户取消选中示例中显示的复选框,但有些人只是忽略了...
$ddlHeader.attr('selectedIndex', 0);
http://jsfiddle.net/abuhamzah/9YM4P/
http://jsfiddle.net/abuhamzah/9YM4P/
//html:
//html:
Header:
<br /><input id="check" type="checkbox" name="approve" />
<select id="myddl" name="myddl">
<option value="0">select me</option>
<option value="1">One</option>
<option value="2">Twooo</option>
<option value="3">Three</option>
</select>
?
?
//js
//js
var $ddls = $('select');
var $check = $('#check');
var $ddlHeader = $("#myddl");
$ddls.prop("disabled", true);
$check .click(function() {
$ddls.prop("disabled", true);
$ddlHeader.prop("disabled", !this.checked);
$ddlHeader.attr('selectedIndex', 0);
});
回答by gdoron is supporting Monica
$ddlHeader.find('option:first').prop('selected', 'selected');
Update:
更新:
$('select').prop('selectedIndex', 0);
Or with more code but more flexible:
或者使用更多代码但更灵活:
$('select').each(function() {
$(this).find('option:first').prop('selected', 'selected');
});
回答by Selvakumar Arumugam
回答by zerkms
UPD:
更新:
I confused selectedIndex
and value. So this solution would work only if you explicitly want the value = 0 to be selected:
我迷茫selectedIndex
和珍惜。因此,仅当您明确希望选择 value = 0 时,此解决方案才有效:
Use val(0)
instead
使用val(0)
替代
$check.click(function() {
$ddls.prop("disabled", true);
$ddlHeader.prop("disabled", !this.checked);
$ddlHeader.val(0);
});
回答by Mohan
//This line of code works for me.
$(function(){$("select").each(function (i) {
$(this).prop("selectedIndex", 0);
});
});
//这行代码对我有用。
$(function(){$("select").each(function (i) {
$(this).prop("selectedIndex", 0);
});
});