I have the following code :
$(document).on("change", "[data-name=country] select", function () {
var country = $("[data-name=country] select").val();
if (country != "") {
$("[data-name=capital] input").val(country);
} });
Of course, this code adds the country name to the "capital" field. I would like to create an array where I would indicate the capital city for each country, so as the capital is added to the field instead of the country.
I know this is a basic question, I wouldnt' have any problem to do that with PHP with an array, but I'm just beginning with javascript and I can't find the correct syntax.
Thank you very much !
CodePudding user response:
You can declare a global object and use similarly to a php's associative array like this:
let countries = {
'Country1': 'Capital1',
'Country2': 'Capital2'
};
let countryName = 'Country1';
console.log(countries[countryName]);
CodePudding user response:
Here's a working example of what I think you're describing. Notice how you can grab the 'associative array' value for the chosen country:
countries[$(this).val()]
let countries = {
'Australia': 'Canberra',
'Switzerland': 'Bern'
};
$(document).ready(function() {
for (let x in countries) $('select[name=countries]').append(`<option value='${x}'>${x}</option>`);
$('form[data-name=country]').on("change", "select[name=countries]", function() {
if ($(this).val()) $('.cap span').text(countries[$(this).val()])
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form data-name='country'>
<select name='countries'><option></option></select>
<hr>
<div class='cap'>Capital: <span></span></div>
</form>