Search code examples
javascriptjqueryhtmldjangoinnerhtml

Dynamically change span text based on selected option javascript


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.


Solution

  • 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>