I have the following JS for generating a dropdown list for provinces/states:
var populateList = function (list, element) {
element.append("<option val=''>Select...</option>")
list.forEach(function (val) {
element.append("<option val=" val[0] ">" val[1] "</option>");
})
}
var canProvinces = [
['ON', 'Ontario'],
['QC', 'Quebec'],
['NS', 'Nova Scotia'],
['NB', 'New Brunswick'],
['MB', 'Manitoba'],
['BC', 'British Columbia'],
['PE', 'Prince Edward Island'],
['SK', 'Saskatchewan'],
['AB', 'Alberta'],
['NL', 'Newfoundland and Labrador'],
['NT', 'Northwest Territories'],
['YT', 'Yukon'],
['NU', 'Nunavut']];
The idea I'm working towards is when the user switches countries in a form, the system can use populateList()
to switch to a new list whenever the user switches countries. Then I use jQuery to put the province abbreviation in a hidden input field. Here is the code in the form:
<script src="list-of-provices/states-from-above.js"></script>
<input id="UserCountry" value="CA" type="text" /> <!-- to be converted to dropdown when issue resolves -->
<select id="province-select" name="province-select"></select>
<input id="Province" type="hidden"/>
<script>
$(document).ready(function () {
if ($('#UserCountry').val() == 'CA') {
populateList(canProvinces, $("#province-select"));
} else if ($('#UserCountry').val() == 'US') {
populateList(usaStates, $("#province-select"));
}
$('#province-select').bind('input propertychange', function () {
//something wrong here? Returns full name, not 2 letter abbreviation.
console.log($("#province-select").val())
$('#Province').val($("#province-select").val())
})
});
</script>
I haven't got to the Country switching part yet because, despite everything I've tried, $("#province-select").val()
returns the Text from the dropdown, not the value. I have not been able to find a reason for this. Here is the HTML generated by the code:
<select id="province-select" name="province-select">
<option val="">Select...</option>
<option val="ON">Ontario</option>
<option val="QC">Quebec</option>
<option val="NS">Nova Scotia</option>
<option val="NB">New Brunswick</option>
<option val="MB">Manitoba</option>
<option val="BC">British Columbia</option>
<option val="PE">Prince Edward Island</option>
<option val="SK">Saskatchewan</option>
<option val="AB">Alberta</option>
<option val="NL">Newfoundland and Labrador</option>
<option val="NT">Northwest Territories</option>
<option val="YT">Yukon</option>
<option val="NU">Nunavut</option>
</select>
Is there something I am missing? $("#province-select").val()
should return the val="" from the dropdown, but for me it returns the text.
Any thoughts?
CodePudding user response:
You have a small mistake in your code. The attribute to be used for setting the value of option is value
and not val
. Replace your
element.append("<option val=" val[0] ">" val[1] "</option>");
with
element.append("<option value='" val[0] "'>" val[1] "</option>");
and you are good.