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 !
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]);
EDIT:
Based on your example, you should first declare the countries object globally (outside of your document ready function) so that it is accessible from everywhere, including inside your function. Then since you have the country, you should try and get the capital from the object. Lastly, you should check if the capital variable contains a truthy value (not being, null, empty, undefined etc.), just in case you provide a country that you have not registered and proceed passing it to your element.
let countries = {
'Country1': 'Capital1',
'Country2': 'Capital2'
};
$(document).on("change", "[data-name=country] select", function () {
let country = $("[data-name=country] select").val();
let capital = countries[country];
if (capital) {
$("[data-name=capital] input").val(capital);
}
});
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>