Javascript 使用 Jquery 更改我的下拉列表的选定索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14711397/
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
Changing the selected index of my dropdown using Jquery
提问by Guy code man
Hello all i am trying to change one dropdowns selected index once another is changed, and i want to use jquery to select the dropdowns. Here is some of my code:
大家好,我正在尝试更改一个下拉列表选择的索引,一旦另一个被更改,我想使用 jquery 来选择下拉列表。这是我的一些代码:
<div id = "monthlist">
<select name = "months">
<option value = 1 > January </option>
<option value = 2 > Febuary </option>
<option value = 3 > March </option>
<option value = 4 > April </option>
<option value = 5 > May </option>
<option value = 6 > June </option>
<option value = 7 > July </option>
<option value = 8 > August </option>
<option value = 9 > September </option>
<option value = 10 > October</option>
<option value = 11 > November </option>
<option value = 12 > December </option>
</select>
</div>
<div id = "yearlist">
<select name = "years">
<option value = 1993 > 1993 </option>
<option value = 1994 > 1994 </option>
<option value = 1995 > 1995 </option>
<option value = 1996 > 1996 </option>
<option value = 1997 > 1997 </option>
<option value = 1998 > 1998 </option>
<option value = 1999 > 1999 </option>
<option value = 2000 > 2000 </option>
<option value = 2001 > 2001 </option>
</select>
</div>
The JQuery code is here:
JQuery 代码在这里:
$("#monthlist").change(function(){
$("select#yearlist").prop('selectedIndex', 2);
});
I want to set the selected index of "yearlist" to a specific index once the monthlist dropdown is changed. But my selector or my code is incorrect, any suggestion or tips will be greatly appreciated.
一旦月列表下拉列表更改,我想将“yearlist”的选定索引设置为特定索引。但是我的选择器或我的代码不正确,任何建议或提示将不胜感激。
回答by Reinstate Monica Cellio
You're trying to select the month and year lists by their names. Use the ID of the outer divs instead...
您正在尝试按名称选择月份和年份列表。使用外部 div 的 ID 代替...
$("div#monthlist select").change(function(){
$("div#yearlist select")[0].selectedIndex = 2;
});
回答by Suresh Atta
is it you are looking for ??
是你要找的吗??
$("#monthlist").change(function(){
$("#yearlist").get(0).selectedIndex = 2;
}
And correction to your case :
并更正您的情况:
$("#monthlist").change(function(){
$("select#yearlist").attr('selectedIndex', 2);
}
And one more choice for index
索引的另一种选择
$("#monthlist").change(function(){
$('#yearlist option').eq(2).attr('selected', 'selected');
}

