Reputation: 4701
I have a form where a user selects a country from a list. When the page loads either the first country in the list, or the country of the user that has been set previously is shown.
If the selected country is one that is in an array EUcountries
, a div with a field is shown.
var EUcountries = [
"AD",
"BE",
"BG",
];
// this is for when the page loads
var inputCountry = $("#countries").val();
if ($.inArray(inputCountry, EUcountries) != -1) {
$('#EUdiv').show();
}
else {
$('#EUdiv').hide();
}
// this is for when the user selects a country.
$("#countries").on('input', function () {
var inputCountry = $("#countries").val();
if ($.inArray(inputCountry, EUcountries) != -1) {
$('#EUdiv').show();
}
else {
$('#EUdiv').hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="countries" name="countries" class="form-control">
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
<option value="AS">American Samoa</option>
<option value="AD">Andorra</option>
<option value="AO">Angola</option>
<option value="AI">Anguilla</option>
<option value="AQ">Antarctica</option>
<option value="AG">Antigua & Barbuda</option>
<option value="AR">Argentina</option>
<option value="AM">Armenia</option>
</select>
<br>
<div id="EUdiv">
<input id="euField">
</div>
As you can see I am setting var inputCountry
once the page loads (because the country can already be set) and every time the input is changed.
Is this the way to go or will I run into problems?
(Select Andorra to see it work)
Upvotes: 1
Views: 110
Reputation: 207537
The issue you have is you are duplicating code. So you have the same code twice. Just have the code once.
Use trigger
$("#countries").on('input', function () {
var inputCountry = $("#countries").val();
if ($.inArray(inputCountry, EUcountries) != -1) {
$('#EUdiv').show();
} else {
$('#EUdiv').hide();
}
}).trigger("input");
or make it a function call.
var countyChange = function () {}
$("#countries").on('input', countyChange)
countyChange()
Now if you have to alter the code, you are doing it in one place and not two.
Upvotes: 3