Search code examples
javascripthtmlselectdropdown

Using <p> tags why has oversight here become so petty, self righteous, anal, unforgiving & passive aggressive? It's a code forum. BTW -1


How do I capture the option Label (not Value) from a select dropdown and create a h1 heading when the option is selected. I also need to ignore the "Please Choose" selection? The heading should only be created if an option is selected (other than Please Choose).Thanks

  <select name="cars" id="cars">
    <option value="" selected>Please Choose</option> 
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
</select>

I need <h1>Audi</h1> not <h1>audi</h1>


Solution

  • This will work for me:

    <select name="cars" id="cars">
      <option value="" selected disabled>Please Choose</option> 
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="opel">Opel</option>
      <option value="audi">Audi</option>
    </select>
    
    <h1 id="carSelected"></h1>
    
    

    and

    //target the element
    var sel = document.querySelector('#cars');
    
    //attach the event
    sel.addEventListener('change', function(){
      //get and set the value
     if (document.getElementById('cars').value != ""){ 
      document.querySelector('#carSelected').textContent = this.options[this.selectedIndex].text;
      }
    });
    
    // execute the event on page load
    var event = new Event('change');
    sel.dispatchEvent(event);
    
    

    Thanks all for your help in helping me figure it out