I have a select field with the list of countries. And I want to show something ONLY for the US selection, and something else for !US selections. But I also want it to do something else when NOTHING is selected. The problem is, Nothing is also inclusive in a non-US selection.
Thanks in advance. Here’s the code:
var selectedCountry, selectAutograph
$('.country, .autograph').on('change', function() {
selectedCountry = $('.country').find('option:selected').val();
selectAutograph = $('.autograph').is(":checked")
if (selectedCountry === "United States" && !selectAutograph) {
console.log("Show US Only");
$(".us").show();
$(".int, .intauto, .usauto").hide();
} else if (selectedCountry !== "United States" && !selectAutograph) {
console.log("Show Int Only");
$(".int").show();
$(".us, .intauto, .usauto").hide();
} else if (selectedCountry === "United States" && selectAutograph) {
console.log("Show US and Autograph");
$(".usauto").show();
$(".intauto, .us, .int").hide();
} else if (selectedCountry !== "United States" && selectAutograph) {
console.log("Show Int and Autograph");
$(".intauto").show();
$(".usauto, .us, .int").hide();
} else {
console.log("Show Nothing");
$(".intauto, .usauto, .us, .int").hide();
}
});
.hide {
display: none;
}
<form id="order-form" method="post" role="form">
<select class="country" name="country" id="country">
<option value="Select Country">Select Country</option>
<option value="United States">United States</option>
<option value="Canada">Canada</option>
<option value="United Kingdom">United Kingdom</option>
<!-- ... -->
<option value="Zimbabwe">Zimbabwe</option>
</select>
<div class="form-check">
<input class="autograph" type="checkbox" value="" id="autograph" name="autograph">
<label class="form-check-label"> Add autograph </label>
</div>
</form>
<div>
<div class="us hide">
US shipping
</div>
<div class="int hide">
International shipping
</div>
<div class="usauto hide">
US shipping + add autograph
</div>
<div class="intauto hide">
International shipping + add autograph
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here’s a JSFiddle as well.
2
Answers
The
else
will never run because theSelect Country
country option will run in theselectedCountry !== "United States" && !selectAutograph
orselectedCountry !== "United States" && selectAutograph
condition, Also you can simplify the code, by addingdata
atttibutes.Please check this.
While you’ve already accepted an answer, I wanted to offer an alternative approach:
JS Fiddle demo.
This is, of course, perfectly possible with plain JavaScript:
References:
Array.prototype.forEach()
.HTMLOptionElement
.find()
.hide()
.is()
.on()
.prop()
.show()
.