I'm trying to change the selected option depending on the other and reverse. but when i do that multiple times, the dropdown block, can i have some help to improve it if possible.
var $select1 = $( '#select1' ),
$select2 = $( '#select2' );
$select1.on( 'change', function() {
var a = $(this).val();
$( "#select2 option[value='" a "']" ).attr("selected", "selected");
});
$select2.on( 'change', function() {
var a = $(this).val();
$( "#select1 option[value='" a "']" ).attr("selected", "selected");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="2">Bear</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
CodePudding user response:
You need to set the value to the select field not the option.
const $select = $('.select');
$select.on( 'change', function() {
const that = $(this);
const a = that.val();
$select.not(that).val(a);
// if you want to get the text from the selected option you can do as follow:
$select.each(function() {
console.log($(this).find('option:selected').text());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="select1" id="select1" >
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2" >
<option value="1">Banana</option>
<option value="2">Bear</option>
<option value="3">Hawk</option>
<option value="4">BMW</option>
</select>