Dynamically change span text based on selected option javascript

偶尔善良 提交于 2019-12-11 13:51:08

问题


I'm trying to change dynamically the text of a span based on the the option that got selected. PS: I'm using Django + Python to generate options

Here is my code :

<select class="form-control" id="materials">
    {% for material2 in materials %}
        <option value="{{ material2.name }}">{{ material2.name }}</option>
    {% endfor %}
</select>
<span id="material_display></span>

I've tried :

var selected_material = document.getElementById("materials").value;
document.getElementById("material_display").innerTEXT = selected_material

But that didn't work out.


回答1:


It's innerText, not innerTEXT and the id of your span is not closed properly; you only have one quotation mark to the left of the id and are missing the quotation mark to the right of the id.

You also need to attach your function to an Event Handler like onchange for your select.

<select id="materials" onchange="showChange()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
<span id="material_display"></span>
<script>
function showChange(){
var selected_material = document.getElementById("materials").value;
document.getElementById("material_display").innerText = selected_material;
}
</script>


来源:https://stackoverflow.com/questions/51561897/dynamically-change-span-text-based-on-selected-option-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!