I am trying to populate a SELECT dropdown list with an array of objects using JavaScript and then display properties of that object based on the option selection. So far I have been able to populate the dropdown, however I can't seem to get the output correctly, as it only selects the last value in the for loop and hence only outputs the last object, for each selection. I thought this might be a closure issue, but I have gone through a lot closure solutions and none seem to work. How can I get each option selection to display the right object properties?
<html>
<body>
<input type="button" onclick="populateSelect()" value="Click to Populate SELECT" />
<!--The SELECT element.-->
<select id="sel" onchange="show()">
<option value="">-- Select --</option>
</select>
<p id="msg"></p>
</body>
<script>
// THE ARRAY.
var birds = [
{ID: 001, Bird_Name: "Eurasian Collared-Dove"},
{ID: 002, Bird_Name: "Bald Eagle"},
{ID: 003, Bird_Name: "Cooper's Hawk"},
];
function populateSelect() {
var ele = document.getElementById('sel');
for (var i = 0; i < birds.length; i++) {
// POPULATE SELECT ELEMENT WITH JSON.
ele.innerHTML = ele.innerHTML +
'<option>' + birds[i]['Bird_Name'] + '</option>';
}
}
function show() {
// GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
var msg = document.getElementById('msg');
for (var i = 0; i < birds.length; i++)
{
msg.innerHTML = birds[i].ID + " " + birds[i].Bird_Name;
}
}
</script>
</html>
e.valueor if you want the text of the select,e.text. Parseeas a parameter in youronchange, since you're doing it inline, rather than using an eventlistener.