简体   繁体   English

使用所选选项更改跨度文本

[英]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.例如,当我 select 总线选项时,我希望它显示“总线”文本。 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.您可以先this关键字传递给 function 然后使用selectedIndex选项获取文本。

 <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.如果您保留 HTML 中的内联声明(通常是首选方法),您可以在单独的文件中分配您的事件处理程序。 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!另外,请注意 - 如果您以传统方式提交表单数据(而不是使用 AJAX 等),那么select元素需要一个名称 - ID 不会出现在 REQUEST 数组中!

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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