Reputation: 767
Suppose I have two Selectbox like this
<select id="emp">
<option value="emp1"> Emp Name 1</option>
<option value="emp2"> Emp Name 2</option>
<option value="emp3"> Emp Name 3</option>
<option value="emp4"> Emp Name 4</option>
</select>
<select id="salary">
<option value="sal1"> $1000</option>
<option value="sal2"> $2000</option>
<option value="sal3"> $3000</option>
<option value="sal4"> $4000</option>
</select>
Here both selectbox have same no of options. Now if anyone select $3000 from salary selectbox, the emp selectbox will be automaticaly selected the value "Emp Name 3" or anyone select a value i.e "Emp Name 2" from emp selectbox then salary selectbox will be automaticaly selected the value $2000. But the problem is I can't understand how to do it. So if anyone have any idea about that please let me know.
Upvotes: 0
Views: 1407
Reputation: 171669
Simplest is use the selectedIndex
property of <select>
. Within a change handler get the current value and assign to the other select
var $selects = $('#emp, #salary').on('change', function(){
$selects.not(this).prop('selectedIndex', this.selectedIndex)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="emp">
<option value="emp1"> Emp Name 1</option>
<option value="emp2"> Emp Name 2</option>
<option value="emp3"> Emp Name 3</option>
<option value="emp4"> Emp Name 4</option>
</select>
<select id="salary">
<option value="sal1"> $1000</option>
<option value="sal2"> $2000</option>
<option value="sal3"> $3000</option>
<option value="sal4"> $4000</option>
</select>
Upvotes: 1
Reputation: 729
You can make this by getting the index of the selected option when the select element change and then changing the option in the other select element.
Here is the code:
$('#emp').on("change", function(){
var index = $('#emp')[0].selectedIndex;
$("#salary").prop('selectedIndex', index);
})
$('#salary').on("change", function(){
var index = $('#salary')[0].selectedIndex;
$("#emp").prop('selectedIndex', index);
})
My fiddle: https://jsfiddle.net/arz1wmLj/4/
Upvotes: 1