Select List Onchange

Use onchange function to display current select list value.

by Paul Leech

HTML

<section>
  <select id="choice" >
    <option value="default" selected>Choose a Value</option>
    <option value="first">First Value</option>
    <option value="second">Second Value</option>
    <option value="third">Third Value</option>
  </select>
  <div class="spacer"></div>
  <div id="showVal"></div>
</section>

CSS

#choice {
  font-size: 1.25rem;
  padding: 5px 8px;
  color: #fff;
  background:#555;
}

#choice option:nth-of-type(odd){
  color: #000;
  background:#ccc;
}

#choice option:nth-of-type(even){
  color: #fff;
  background:#999;
}
#choice option::hover {
  color: #fff;
  background:#999;  
}

section {
  font-family: sans-serif;
  width: 300px;
  height: 100px;
  margin: 0 auto;
  font-size: 1.25rem;
  border: 2px groove #ccc;
  border-radius:1rem;
  text-align:center;
}

.spacer {
  height:12px;
}

JavaScript

const showVal = document.getElementById('showVal');

document.getElementById('choice').onchange = function() {
  // alert(this.value);
  let selectedText = this.options[this.selectedIndex].innerHTML;
  let selectedValue = this.value;
  showVal.innerHTML = `Selected Text: <strong>${selectedText}</strong><br>Selected Value: <strong>${selectedValue}</strong>`;
}