简体   繁体   中英

Change span text with selected option

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>

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM