jQuery: Change selection of 2nd dropdown based on selection of 1st

╄→гoц情女王★ 提交于 2019-12-08 12:48:26

问题


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());
});

回答1:


From what you're describing it seems like you want to have the selectedIndex in sync.

Here's how:

jsFiddle Example

$(function() {
    $("#dropdwon1").change(function() {
        $("#dropdwon2")[0].selectedIndex = $(this)[0].selectedIndex;
    });
});​



回答2:


$("#dropdwon1").change(function(){
   $("#dropdwon2").val( +this.value + 2 );
});

DEMO

+this.value will converted into number so you can add 2.

OR

$("#dropdwon1").change(function(){
   $("#dropdwon2").prop('selectedIndex', this.selectedIndex );
});

DEMO




回答3:


This works:

$('#dropdown1').change(function(){
   var ind = $(this).find('option:selected').index();
   $('#dropdown2 option').eq(ind).prop('selected', true);
});



回答4:


var ac1=$("#dd1").val();
$("#dd2").val(ac1);


来源:https://stackoverflow.com/questions/11889030/jquery-change-selection-of-2nd-dropdown-based-on-selection-of-1st

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!