jQuery: Change selection of 2nd dropdown based on selection of 1st
-
25-06-2021 - |
Question
I have two drop down lists and I would like to make it when someone selects value 2 from dropdown1, dropdown2 is automatically changed to value 4.
<select id="dropdwon1">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3">Item3</option>
</select>
<select id="dropdwon2">
<option value="3">Item1</option>
<option value="4">Item2</option>
<option value="5">Item3</option>
</select>
I have seen how this can be done when the values are the same but not when they are different. Looking for a simple solution like this below.
$("#dropdwon1").change(function(){
$("#dropdwon2").val($(this).val());
});
Solution
From what you're describing it seems like you want to have the selectedIndex
in sync.
Here's how:
$(function() {
$("#dropdwon1").change(function() {
$("#dropdwon2")[0].selectedIndex = $(this)[0].selectedIndex;
});
});
OTHER TIPS
This works:
$('#dropdown1').change(function(){
var ind = $(this).find('option:selected').index();
$('#dropdown2 option').eq(ind).prop('selected', true);
});
var ac1=$("#dd1").val();
$("#dd2").val(ac1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow