<form action="#" method="post" id="demoForm" class="demoForm">
<fieldset>
<legend>Demo: Get Value or Text of Selected Option in Select Box</legend>
<p>
<select id="scripts" name="scripts">
<option value="scroll">Scrolling Divs JavaScript</option>
<option value="tooltip">JavaScript Tooltips</option>
<option value="con_scroll" selected="selected" >Continuous Scroller</option>
<option value="banner">Rotating Banner JavaScript</option>
<option value="random_img">Random Image PHP</option>
<option value="form_builder">PHP Form Generator</option>
<option value="table_class">PHP Table Class</option>
<option value="order_forms">PHP Order Forms</option>
</select>
<input type="text" size="30" name="display" id="display" />
<p>
Selected Option Value
</p>
<input type="text" size="25" name="selOpt" id="selOpt" />
<p>
<input type="button" id="showVal" value="Value Property" />
<input type="button" id="showTxt" value="selectedIndex/Text" />
<input type="button" id="doLoop" value="Value from Loop" />
<input type="button" id="showIndex" value="Index Value" />
</p>
</fieldset>
</form>
JavaScript
(function() {
// get references to select list and display text box
var sel = document.getElementById('scripts');
var disp = document.getElementById('display');
var selOpt = document.getElementById('selOpt');
selOpt.value = sel.value;
function getSelectedOption(sel) {
var opt;
for ( var i = 0, len = sel.options.length; i < len; i++ ) {
opt = sel.options[i];
if ( opt.selected === true ) {
break;
}
}
return opt;
}
// assign onclick handlers to the buttons
// update on selection
document.getElementById('scripts').onclick = function () {
disp.value = "";
selOpt.value = sel.value;
}
document.getElementById('showVal').onclick = function () {
disp.value = sel.value;
}
document.getElementById('showTxt').onclick = function () {
// access text property of selected option
disp.value = sel.options[sel.selectedIndex].text;
}
document.getElementById('doLoop').onclick = function () {
var opt = getSelectedOption(sel);
disp.value = opt.value;
}
document.getElementById('showIndex').onclick = function () {
// access index property of selected option
var opt = getSelectedOption(sel);
disp.value = opt.index;
}
}());
// immediate function to preserve global namespace
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.