Reputation: 94
I'm creating a select based on the JSON I got with an API. Based on that select, when I choose another option I want some data to change (text and image src).
I got the select with the options done. Each option is a name and I done that with forEach. My problem is setting the value so I can use it to change the other data. In my mind the easiest solution would be setting the value to the objects index so when I choose the first option I get 0 and can get the first JSON object. I'm not sure if this is the best way anyway.
This is my code reduced to only the forEach:
<select name="select" id="selector"> </select>
data_json.show.forEach((element) => {
document.getElementById('selector').innerHTML +=
`<option value="">${element.name}</option>`;
});
(the value is what I want to be the same as the index of each json data)
My idea of what I want to get:
<select name="select" id="selector">
<option value="0">Name_01</option>
<option value="1">Name_02</option>
<option value="2">Name_03</option>
</select>
So I can use the value like this:
let titulos = document.getElementById("titulos");
selectVal.onchange = function() {
let actualVal = selectVal.options[selectVal.selectedIndex].value;
titulos.innerHTML = "Títulos:" + " " + data_json.show[actualVal].image;;
};
<p id="titulos">Títulos:</p>
Hope it makes sense
Upvotes: 0
Views: 2092
Reputation: 782305
You're setting them all to an empty value. You can use the array index to give them each a different value.
data_json.show.forEach((element, index) => {
document.getElementById('selector').innerHTML +=
`<option value="${index+1}">${element.name}</option>`;
});
BTW, you can simplify selectVal.options[selectVal.selectedIndex].value
to just selectVal.value
.
Upvotes: 3