2 dropdowns with similar options but 1 change in options. In the first dropdown Audi exists but not in second dropdown.
This selects the same option in each dropdowns when selected as required.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="cars">Choose a car:</label>
<select name="cars" id="cars1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
<label for="cars">Choose a car:</label>
<select name="cars" id="cars2">
<option value="">Please-Select</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
</select>
$(document).on('change', '[name="cars"]', function(){
$('[name="cars"]').val( $(this).val() );
})
When I select the “Audi” option, how do I select “Please-Select” option while retaining the current functionality.
2
Answers
Changed the selectors, to select by
ID
.Saved the selected value in a variable, and on change, checking if the value is audi, then the selected value on the second
select="cars"
will be the empty value, which isPlease-select
.NOTES:
select
as the first one. Deleting this function won’t affect your requirements. Feel free to modify it as you like.for
attribute is to target the input that related tolabel
, and it has to be theid
of the targetinput
which is a unique value, so I changed thefor
attributes values to match theid
‘s of theinputs
.name
attribute in an HTML form. However, it can lead to unexpected behavior when submitting the form.The Code:
I have added IDs to both selects for a easier selection.
Then you test the selected option in #2. If it exists, select it. If not, select the default option.
This way of testing against an existing match will allow to add values without worrying about the second select or differences.
Here’s a working pen as I can’t add a snippet.