I have some javascript that is supposed to fill an input field based on the selection made in a dropdown. It uses a json file in the background to lookup the values. The JSON looks like this:
"name":"Netherlands",
"alpha3":"NLD",
Connection to the json works and all the values (countries in this case) are visible in the dropdown. But when I select a value in the dropdown an input field should be auto filled with the alpha3 value from the json.
This is not working right, the input field is always filled with the last alpha3 value in the JSON file (called ZZZ) and not with the one corresponding to the selected option.
What am I doing wrong?
let dropdown = document.getElementById('landen');
dropdown.length = 0;
let defaultOption = document.createElement('option');
defaultOption.text = 'Selecteer land';
dropdown.add(defaultOption);
dropdown.selectedIndex = 0;
const url = 'lib/jsondata/landenmetcodes.json';
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status === 200) {
const data = JSON.parse(request.responseText);
let option;
for (let i = 0; i < data.length; i++) {
option = document.createElement('option');
option.text = data[i].name;
option.value = data[i].name;
dropdown.add(option);
tekst = data[i].alpha3;
document.getElementById("landen").addEventListener("change", myFunction);
function myFunction() {
var x = document.getElementById("landcode");
x.value = tekst;
}
}
} else {
// Reached the server, but it returned an error
}
}
request.onerror = function() {
console.error('An error occurred fetching the JSON from ' + url);
};
request.send();
myFunction is a event callback and is triggered only when event is fired. You are trying to use a local variable from ajax callback in event callback. By the time event is fired "tekst" is not available anymore. You can save the json in global variable and then use that in event callback
let dropdown = document.getElementById('landen');
dropdown.length = 0;
let jsOptions = {};
let defaultOption = document.createElement('option');
defaultOption.text = 'Selecteer land';
dropdown.add(defaultOption);
dropdown.selectedIndex = 0;
document.getElementById("landen").addEventListener("change", myFunction);
function myFunction(evt) {
const val = evt.target.value;
var x = document.getElementById("landcode");
x.value = jsOptions[val];
}
const url = 'lib/jsondata/landenmetcodes.json';
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status === 200) {
const data = JSON.parse(request.responseText);
let option;
for (let i = 0; i < data.length; i++) {
option = document.createElement('option');
option.text = data[i].name;
option.value = data[i].name;
dropdown.add(option);
jsOptions[data[i].name] = data[i].alpha3;
}
} else {
// Reached the server, but it returned an error
}
}
request.onerror = function() {
console.error('An error occurred fetching the JSON from ' + url);
};
request.send();