firstly sorry but I didn’t understand how we passed those parameters to the displayCountriesOptions()
forEach loop
Here:
arr.forEach(({ uuid, country_name, "iso-3166": alpha2Code })
The forEach
callback function receives, as the first parameter, the element being iterated, right? The previous code is exactly the same as this:
const uuid = el.uuid,
country_name = el.country_name,
alpha2Code = el['iso-3166'];
This expression is called object destructuring
, and is just a shorter way to assign variables. It works with arrays too: const [a, b, c] = [1, 2, 3] // a = 1, b = 2, c = 3
.
Read more about destructuring here.
this gave error ReferenceError: iso3166 is not defined
That’s because you changed the variable name here: arr.forEach(({ uuid, country_name, "iso-3166": alpha2Code })
Even if you rename it as iso3166
the code won’t work correctly. The idea is fine, but here:
if (e.target.classList.contains('label-text')) {
selected_country.innerText = e.target.innerText;
let selected_input = selected_country.querySelector('.category');
// console.log(selected_country.innerText);
console.log(selected_input.value)
selected_country.dataset.iso = selected_input.value;
}
The problem is that selected_country.querySelector('.category');
will return the first element with a class of category
, but since there are as many as countries are, then it will not be correct one (unless the user selects the first element on the list).
To fix it, you need to attach the listener to each div.option
instead:
let div = document.createElement("div");
div.className = "option";
// SKAP: Add the value of the iso code (required by the API)
div.innerHTML = `
<label class="label-text" for="${uuid}">${country_name}</label>
<input type="radio" class="radio" id="${uuid}" value="${iso3166}" name="category">
`;
options_country.appendChild(div);
div.addEventListener("click", (e) => {
// Here you handle each element click
options_cont.innerHTML = "";
const { currentTarget: target } = e;
const input = target.querySelector("input"),
label = target.querySelector("label");
// Handle the rest of the logic
});