James
James

Reputation: 37

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?

To give context, in my case this is to update the price shown in the <span></span> to the corresponding value of the selection.

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

Upvotes: 1

Views: 3088

Answers (2)

digital-pollution
digital-pollution

Reputation: 1074

var selectElement = document.getElementById('classesPW');

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

Upvotes: -1

Rafik Tighilt
Rafik Tighilt

Reputation: 2101

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.

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>

Upvotes: 3

Related Questions