Display selected option into a Div

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts:107

Display selected option into a Div

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>

MarPlo Posts:186
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:

Similar Topics