Here is code I wrote to dynamically choose between three country options (United States, Canada, Other). After the user selects a country it will show the related select option or an empty input (when "Other" country is chosen). Then I pass the previous value into an input called spr(state/province/region). The end result is two values are saved: country and spr.
I'm here because I think the code could be refactored, and I'm not thinking about it in an efficient way.
const country = '#country';
const province = '#province';
const region = '#region';
const state = '#state';
const spr = '#spr';
const usa = '#usa';
const canada = '#canada';
const otherCountry = '#otherCountry';
hideCountryOptions(); //initial hide
$(country).on('change', function() {
hideCountryOptions();
selectSPR($(country).val());
switch ($(country).val()) {
case "UNITED STATES":
$(usa).show();
break;
case "CANADA":
$(canada).show();
break;
default:
$(otherCountry).show();
}
})
$(state + "," + province + "," + region).on('change', function() {
selectSPR($(country).val());
});
function hideCountryOptions() {
$(canada).hide();
$(usa).hide();
$(otherCountry).hide();
}
function selectSPR(country) { //pass value into the state/province/region input
$(spr).val("");
switch (country) {
case "UNITED STATES":
$(spr).val($(state).val());
break;
case "CANADA":
$(spr).val($(province).val());
break;
default:
$(spr).val($(region).val());
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label for="country">*Country</label>
<select name="country" id="country" required>
<option value="">CHOOSE…</option>
<option value="UNITED STATES">UNITED STATES</option>
<option value="CANADA">CANADA</option>
<option value="AFGHANISTAN">AFGHANISTAN</option>
</select>
</div>
<div id="usa">
<label for="state">*State</label>
<select name="state" id="state">
<option value="">CHOOSE...</option>
<option value="ALABAMA">ALABAMA</option>
<option value="ALASKA">ALASKA</option>
</select>
</div>
<div id="canada">
<label for="province">*Province</label>
<select class="custom-select" name="province" id="province">
<option value="">CHOOSE...</option>
<option value="ALBERTA">ALBERTA</option>
<option value="BRITISH COLUMBIA">BRITISH COLUMBIA</option>
</select>
</div>
<div id="otherCountry">
<label for="region">*Region</label>
<input type="text" name="region" id="region" placeholder="Region">
</div>
<div>
<input type="text" name="spr" id="spr">
</div>