Answers for "how to get the value from selected option in javascript"

6

html get selected option javascript

<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>

<script>
    var e = document.getElementById("ddlViewBy");
	var strUser = e.value; // 2
	var strUser = e.options[e.selectedIndex].text; //test2
</script>
Posted by: Guest on December-10-2020
6

get selected value of dropdown in javascript

<body>
   
   <select id="list" style="padding: 10px;" onchange="getSelectValue();">
     <option value="js">JavaScript</option>
     <option value="php">PHP</option>
     <option value="c#">Csharp</option>
     <option value="java">Java</option>
     <option value="node">Node.js</option>
   </select>
   
    <script>
        function getSelectValue()
        {
            var selectedValue = document.getElementById("list").value;
            alert(selectedValue);
        }
        getSelectValue();
    </script>
 </body>
Posted by: Guest on June-12-2020
2

use js to get select value

// reference to 'scripts' select list 
// used throughout the examples below
var sel = document.getElementById('scripts');

// display value property of select list (from selected option)
console.log( sel.value );
Posted by: Guest on February-22-2020
0

js select option value when selected

(function() {
    
    // get references to select list and display text box
    var sel = document.getElementById('scripts');
    var el = document.getElementById('display');


    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
    document.getElementById('showVal').onclick = function () {
        el.value = sel.value;    
    }
    
    document.getElementById('showTxt').onclick = function () {
        // access text property of selected option
        el.value = sel.options[sel.selectedIndex].text;
    }

    document.getElementById('doLoop').onclick = function () {
        var opt = getSelectedOption(sel);
        el.value = opt.value;
    }
    
}());
// immediate function to preserve global namespace
Posted by: Guest on December-27-2020

Code answers related to "how to get the value from selected option in javascript"

Browse Popular Code Answers by Language