1

I am on beginning of the coding life. I am trying to change text in span with selected option, but it gives me values not texts. For example, when I select the bus option, I want it to shows me the "bus" text. I do not want value number. Thanks in advance.

<select id="vehicles" onchange="showChange()">
  <option value="1">Bus</option>
  <option value="2">Car</option>
  <option value="3">Plane</option>
</select>

<span id="vehicle"></span>

<script>
  function showChange(){
    var selected_vehicle = document.getElementById("vehicles").value;
    document.getElementById("vehicle").innerText = selected_vehicle;
  }
</script>
Mamun
  • 66,969
  • 9
  • 47
  • 59
adio sang
  • 23
  • 3
  • Does this answer your question? [retrieving-the-text-of-the-selected-option-in-select-element](https://stackoverflow.com/questions/610336/retrieving-the-text-of-the-selected-option-in-select-element) – Zahra Ahangari Feb 28 '21 at 08:54

2 Answers2

1

You can first pass this keyword to the function then get the text using selectedIndex of option.

<select id="vehicles" onchange="showChange(this)">
  <option value="1">Bus</option>
  <option value="2">Car</option>
  <option value="3">Plane</option>
</select>

<span id="vehicle"></span>

<script>
  function showChange(el){
    var selected_vehicle = el.options[el.selectedIndex].text;
    document.getElementById("vehicle").innerText = selected_vehicle;
  }
</script>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

If you keep the inline declarations from your HTML ( generally the preferred approach ) you can assign your event handlers in a separate file. Also, as a point of note - if you submit the form data in the traditional manner ( rather than with AJAX etc ) then the select element needs a name - an ID will NOT appear in the REQUEST array!

    document.querySelector('select[name="vehicles"]').addEventListener('change',e=>{
        e.target.nextElementSibling.textContent=[ e.target.value, e.target.options[e.target.options.selectedIndex].text].join(' ')
    })
<select name='vehicles'>
  <option selected hidden disabled>Select mode of transport
    <option value='1'>Bus
    <option value='2'>Car
    <option value='3'>Plane
</select>

<span id='vehicle'></span>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46