Meiji Meiji - 4 months ago 23
Javascript Question

How to keep multiple select in sync onChange using jquery

I'm trying to figure out how to keep in sync two or more selects. I actually created several select elements (I'm not sure if this is the most accurate approach, if there's another way I'd be grateful if someone tells me).

If I select

North America
in the first one, only the select with
id="north"
will show automatically and the others will remain hidden, if I change to
Central America
, the rest will change as well, showing only the select with
id="central"
and the rest hidden.

This is what I got so far:

<select id="continent">
<option value="1">North America</option>
<option value="2">Central America</option>
<option value="3">South America</option>
</select>

<select id="north">
<option value="1">Canada</option>
<option value="2">USA</option>
<option value="3">Mexico</option>
</select>

<select id="central">
<option value="1">Guatemala</option>
<option value="2">Costa Rica</option>
<option value="3">Nicaragua</option>
</select>

<select id="south">
<option value="1">Brazil</option>
<option value="2">Argentina</option>
<option value="3">Chile</option>
</select>


So far I've only got to sync two selects with same value:

$("#continent").change(function(){
$("#north").val($("#continent").val())
});


However, this is far from what I need. Could anyone help me figure out the correct approach?

Thanks in advance!

Answer

First you need to select text of selected option and get first part of it that is id of other select. Then hide all siblings of select and show select has specific id.

$("#continent").change(function(){
    var id = $(this).find("option:selected").text().split(" ")[0].toLowerCase();
    $(this).siblings().hide().siblings("#"+id).show();
}).siblings().hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="continent">
    <option value="">Select one</option>
    <option value="1">North America</option>
    <option value="2">Central America</option>
    <option value="3">South America</option>
</select>
<select id="north">
    <option value="1">Canada</option>
    <option value="2">USA</option>
    <option value="3">Mexico</option>
</select>
<select id="central">
    <option value="1">Guatemala</option>
    <option value="2">Costa Rica</option>
    <option value="3">Nicaragua</option>
</select>
<select id="south">
    <option value="1">Brazil</option>
    <option value="2">Argentina</option>
    <option value="3">Chile</option>
</select>

Comments