0

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>
1
  • 1
    If you're successful at populating it, then you don't need another loop to find the selected value. You can use e.value or if you want the text of the select, e.text. Parse e as a parameter in your onchange, since you're doing it inline, rather than using an eventlistener. Commented Jan 31, 2021 at 17:30

2 Answers 2

2

You should use a value for the options and pass that value into your event handler function. Then compare selected value to the elements in array as well as set a default if no value selected

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');
  birds.forEach(function(b) {
    ele.innerHTML += '<option value="' + b.ID + '">' + b['Bird_Name'] + '</option>';
  })

}

function show(id) {
  // GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
  var msg = document.getElementById('msg');
  if (!id) {
    msg.innerHTML = 'None selected';

  } else {
    for (var i = 0; i < birds.length; i++) {
      if (Number(id) === birds[i].ID) {
        msg.innerHTML = birds[i].ID + " " + birds[i].Bird_Name;
        break;
      }
    }
  }
}

populateSelect()
<select id="sel" onchange="show(this.value)">
  <option value="">-- Select --</option>
</select>

<p id="msg"></p>

Sign up to request clarification or add additional context in comments.

Comments

2

You should use the value attribute in tag, also as one of the comment mentions you can make use of the events too.

// THE ARRAY.
var birds = [{
    ID: 001,
    Bird_Name: "Eurasian Collared-Dove"
  },
  {
    ID: 002,
    Bird_Name: "Bald Eagle"
  },
  {
    ID: 003,
    Bird_Name: "Cooper's Hawk"
  },
];

var select = document.getElementById('sel');

function populateSelect() {
  for (var i = 0; i < birds.length; i++) {
    // POPULATE SELECT ELEMENT WITH JSON.
    // add the value attribute in option as the id of bird
    select.innerHTML = select.innerHTML +
      '<option value=' + birds[i].ID + '>' + birds[i]['Bird_Name'] + '</option>';
  }
}

function show() {
  // GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
  var msg = document.getElementById('msg');
  // find the bird with the selected id
  let selectedBird = birds.find(bird => bird.ID == select.value);
  // display the info
  msg.innerHTML = selectedBird.ID + " " + selectedBird.Bird_Name;

}
<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>

</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.