简体   繁体   English

jQuery根据选择更改值

[英]JQuery to change value based on selection

i have 2 dropdownlist, i want if i select Alabama in dropdwon1 the selected value in dropdwon2 should change in to Other.., how to do this using JQuery 我有2个下拉列表,我想如果我在dropdwon1中选择Alabama,则dropdwon2中的选定值应更改为Other ..,如何使用JQuery做到这一点

<select id="dropdwon1">
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
</select>

<select id="dropdwon2">
<option value="3">Item1</option>
<option value="4">Item2</option>
<option value="5">Other..</option>
</select>

You must bind event to first select change event and check it's selected value and set value for second select like this: 您必须将事件绑定到第一个选择更改事件,并检查它的选择值并为第二个选择设置值,如下所示:

//Bind change event to first select
$('#dropdwon1').on('change', function(){

    //check selected value
    var value = $(this).val();
    if(value == 1){

         //Set selected value for second select
         $('#dropdwon2').val(5);
    }
})

You have to initialize your value for the second select for the first value of your state select , like so : 您必须为状态选择第一个值初始化第二个选择的 ,如下所示:

if($("#dropdown1").val()=="1"){
    $("#dropdown2").val("5"); // Set the value (your answer)
} 

then use the change event and give the different values of the second select for the states values. 然后使用change事件,并为状态值提供第二选择的不同值。

As the user can select Alabama again after having chosen another value, you have to put the code for the first value in the change event function. 由于用户在选择另一个值之后可以再次选择阿拉巴马州,因此您必须将第一个值的代码放入change事件函数中。

Here is a jsfiddle : 这是一个jsfiddle:

https://jsfiddle.net/mantisse_fr/ak81o26s/4/ https://jsfiddle.net/mantisse_fr/ak81o26s/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM