0

How do I display the selected option name in the div above it? If user has blue selected I want blue to show above.

<div id='text"> selection goes here</div>
<select id="dropdownselect">
<option> Red </option>
<option> White </option>
<option> Blue </option>
</select>
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
Sam Danger
  • 49
  • 1
  • 2
  • 10

4 Answers4

3

Use the following to get the text of the selected option:

var select = document.getElementById("dropdownselect");
var selectedText = select.options[select.selectedIndex].text;

Then, to add the value to the div with id text, use:

document.getElementById("text").innerHTML = selectedText;

If you want to reflect the selected value every time the option has changed, you need to attach the onchange event to the select, which, combined with the above code results in the following:

var select = document.getElementById("dropdownselect");
select.onchange = function () {
  var selectedText = this.options[this.selectedIndex].text;
  document.getElementById("text").innerHTML = selectedText;
};​

Here's a working DEMO.

João Silva
  • 89,303
  • 29
  • 152
  • 158
1

Just add onchange javascript event:

<div id="text"> selection goes here</div>
<select id="dropdownselect" onchange="document.getElementById('text').innerHTML = this.options[this.selectedIndex].text;">
    <option> Red </option>
    <option> White </option>
    <option> Blue </option>
</select>​​​​​​​​​​​​​​
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
0

You should use a javascript framework to make it much easier. I personally use jQuery, in which case the javascript to get the value is:

$("#dropdownselect").val()

And you can change it automatically with:

<select id="dropdownselect" onChange="$('#text').text($(this).val());">

Similar functions are available with MooTools, or other frameworks I haven't used before.

jQuery can be made available with:

<script src="jquery.js"><!-- assuming you have a jquery file at this location -->
ronalchn
  • 12,225
  • 10
  • 51
  • 61
0
var selectBox = document.getElementById("dropdownselect"),
    textDiv = document.getElementById("text");
textDiv.innerText = selectBox.options[selectBox.selectedIndex].text;

But i'd recommend using jQuery too.

Rafael Adel
  • 7,673
  • 25
  • 77
  • 118