JSFiddle - React, Tailwind, and code Playground

by John Passmore

HTML

<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