Search code examples
javascripthtmldropdown

Problems using dropdown values to reference a JavaScript object


I'm working on a table that will populate based on what is selected in a drop-down menu, however when a selection is made the output shows as undefined. I am attempting to use the dropdown value to reference an object within a function. I am wondering if the value from the dropdown is unable to be used to reference the function or if the value needs to be changed somehow to work properly in the script.

I am new to Javascript, thank you in advance for any advice. Below is a code sample of what I am using.

function fillrow() {
  var selection = document.getElementById("description_dropdown").value;
  const fordmotorco = {
    sector: "Corporate Bonds",
    cusip: "ABC5132",
    coupon: "5%"
  };
  const abbvie = {
    sector: "Corporate Bonds",
    cusip: "A12345HJ",
    coupon: "3%"
  };

  document.getElementById("col0").innerHTML = selection.sector;
  document.getElementById("col1").innerHTML = selection.cusip;
  document.getElementById("col2").innerHTML = selection.coupon;
}
<table id="holdings">
  <thead>
    <th>Sector</th>
    <th>Cusip</th>
    <th>Coupon</th>
  </thead>
  <tr id=select_security_row>
    <td id="col0">-</td>
    <td id="col1">-</td>
    <td id="col2">-</td>
    <td id="col3">
      <select id="description_dropdown" type=text name=Cusip onchange="fillrow(this)">
        <option value="fordmotorco">Ford Motor Co</option>
        <option value="abbvie">Abbvie</option>
      </select>
    </td>
  </tr>
</table>


Solution

  • The value when you make the selection won't change. A better approach is to attach a change event listener to your <select>. See docs addEventListener, change event. So every time you choose an option in the dropdown, the callback function passed in addEventListener will be called.

    Here's the suggested change to your JS code:

    function fillrow(value) {
      const data = {
        fordmotorco: {
          sector: 'Corporate Bonds',
          cusip: 'ABC5132',
          coupon: '5%',
        },
        abbvie: { sector: 'Corporate Bonds', cusip: 'A12345HJ', coupon: '3%' },
      }
      document.getElementById('col0').innerHTML = data[value].sector
      document.getElementById('col1').innerHTML = data[value].cusip
      document.getElementById('col2').innerHTML = data[value].coupon
    }
    
    document
      .getElementById('description_dropdown')
      .addEventListener('change', function (event) {
        fillrow(event.target.value)
      })
    
    
    

    Attached a working demo for a similar example too.