Reputation: 49
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>
Upvotes: 0
Views: 100
Reputation: 91309
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.
Upvotes: 3
Reputation: 39704
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>
Upvotes: 1
Reputation: 7759
var selectBox = document.getElementById("dropdownselect"),
textDiv = document.getElementById("text");
textDiv.innerText = selectBox.options[selectBox.selectedIndex].text;
But i'd recommend using jQuery too.
Upvotes: 0
Reputation: 12335
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 -->
Upvotes: 0