Changing the selected index of my dropdown using jQuery

Hi everyone, I am trying to change one dropdown if one of them is changed, and I want to use jquery to select dropdown menus. Here is my code:

<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> 

JQuery code is here:

 $("#monthlist").change(function(){ $("select#yearlist").prop('selectedIndex', 2); }); 

I want to set the selected index "yearlist" to a specific index after changing the drop-down list. But my selector or my code is wrong, any suggestion or advice would be highly appreciated.

+4
source share
2 answers

You are trying to select monthly and annual lists by their names. Use the identifier of the external divs instead ...

 $("div#monthlist select").change(function(){ $("div#yearlist select")[0].selectedIndex = 2; }); 
+6
source

are you looking for this?

 $("#monthlist").change(function(){ $("#yearlist").get(0).selectedIndex = 2; } 

And the correction to your case:

 $("#monthlist").change(function(){ $("select#yearlist").attr('selectedIndex', 2); } 

And one more choice for the index

 $("#monthlist").change(function(){ $('#yearlist option').eq(2).attr('selected', 'selected'); } 
0
source

All Articles