Page 1 of 1

Display selected option into a Div

Posted: 25 Nov 2020, 14:32
by Marius
How can I make that when an option from dropdowna <select> list is selected, the value of that option be displayed into a Div.
I have this html code, with the list of options and the Div tag:

Code: Select all

<select id='drink'>
  <option value=''>Which drink would you like?</option>
  <option>Latte</option>
  <option>Capuccino</option>
  <option>Americano</option>
  <option>Tea</option>
</select>
<div id='output'></div>

Display selected option into a Div

Posted: 25 Nov 2020, 15:38
by MarPlo
You have to start with a <select> element which raises a 'change' event when an option is selected.
Inside that event, 'this.value' refers to the selected value.

Code: Select all

Select an option: 
<select id='drink'>
  <option value=''>Which drink would you like?</option>
  <option>Latte</option>
  <option>Capuccino</option>
  <option>Americano</option>
  <option>Tea</option>
</select>
<div id='output'></div>

<script>
var drinkSelect = document.getElementById('drink');
var outputDiv = document.getElementById('output');
drinkSelect.addEventListener('change',function(){
  output.innerText = 'You like '+ this.value;
})
</script>
- Demo
Select an option: