Search code examples
javascriptgetelementbyidgetelementsbytagname

Select by id and get the name of the attribute on javascript


I am trying to get a a second value of an element to print it out on another div. This code gives me 'undefined' value. What is wrong with this code? I don't know. What do you think?

<select class="form-control"  id="Workers"  value="Select an id">
 <option id="myInput" onclick="myFunction()" name="personname" value="personid">personid</option>
 <option id="myInput" onclick="myFunction()" name="personname2" value="personid2">personid2</option>
</select>

 <p id="demo"></p>

<script>

 function myFunction() {
    document.getElementById("demo").innerHTML = document.getElementById("myInput").name ;
}

</script>

Solution

  • Here is an example that watches the select element for changes - instead of watching for 'clicks' on an option.

    // cache these elements you're going to use first
    var workerSelect = document.getElementById('worker-select');
    var demoArea = document.getElementById('demo-area');
    
    workerSelect.addEventListener('change', function() {
      // 'this' refers to the thing that the method is called on... so - the select
      // console.log(this); // to see select object
      var selectedOption = this.options[this.selectedIndex];
      var handle = selectedOption.getAttribute('data-handle');
      var label = selectedOption.label;
      demoArea.innerHTML = "handle: " + handle + " | name: " + label;
    });
    <select id="worker-select" name="readAboutIt">
      <option disabled selected="selected">Select a worker</option>
      <option label="Derek Wood" value="1" data-handle="sheriffderek"></option>
      <option label="John Doe" value="2" data-handle="J. Doe"></option>
    </select>
    
    <p id="demo-area"> <!-- output here... --></p>

    data-attr can be anything you want. data-color="red" data-my-favorite-food="?"

    Select: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select

    Option: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option