简体   繁体   English

如何在香草JS中更新dom元素以选择选项值?

[英]How to update dom element to select option value in vanilla JS?

What's the best way to update the text with a DOM element, in this case <span> to the value of a <select> <option> on change in vanilla JS? 在原始JS中更改时,用DOM元素(在这种情况下<span>将其更新为<select> <option>的值的最佳方法是什么?

To give context, in my case this is to update the price shown in the <span></span> to the corresponding value of the selection. 为了说明背景,在我的情况下,这是将<span></span>显示的价格更新为所选内容的相应值。

<select name="classesPW" id="classesPW">
    <option value="5">1</option>
    <option value="9">2</option>
    <option value="12.50">3</option>
    <option value="16">4</option>
    <option value="19">5</option>
    <option value="22">6</option>
    <option value="25">7</option>
    <option value="28">8</option>
    <option value="31">9</option>
    <option value="34">10</option>
    <option value="37">11</option>
    <option value="40">12</option>
</select>

<h3>
    <span>£</span>
    <span id="pwTotal"> [[value here]] </span>
</h3>

You can use querySelector to get your elements, assign a change event listener to the select, and then retrieve the value of the selected item and put it to the span via innerHTML. 您可以使用querySelector来获取您的元素,将更改事件侦听器分配给选择,然后通过innerHTML检索所选项目的值并将其放入跨度。

Working example : 工作示例:

 let select = document.querySelector('#classesPW') let sp = document.querySelector('#pwTotal') select.addEventListener('change', function() { sp.innerHTML = select.options[select.selectedIndex].value }) 
 <select name="classesPW" id="classesPW"> <option value="5">1</option> <option value="9">2</option> <option value="12.50">3</option> <option value="16">4</option> <option value="19">5</option> <option value="22">6</option> <option value="25">7</option> <option value="28">8</option> <option value="31">9</option> <option value="34">10</option> <option value="37">11</option> <option value="40">12</option> </select> <h3> <span>£</span> <span id="pwTotal">5</span> </h3> 

 var selectElement = document.getElementById('classesPW'); selectElement.addEventListener('change', function(e){ var selection = selectElement.options[selectElement.selectedIndex].value; document.getElementById('pwTotal').innerText = selection; }); 

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

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