DEV Community

loading...

How to display selected value of drop down list in HTML

whataluckyguy profile image Lalit Kumar ・1 min read

Solution: You can simply use JavaScript to display the selected value or text from a drop-down list. Let us follow this step

STEP 1: Create a drop box list

<select id="country">
    <option value="None">-- Select --</option>
    <option value="ID001">China</option>
    <option value="ID002" selected>United State</option>
    <option value="ID003">Malaysia</option>
</select>
Enter fullscreen mode Exit fullscreen mode

title: "originally posted here 👇"

canonical_url: https://kodlogs.com/blog/213/how-to-display-selected-value-of-drop-down-list-in-html

STEP 2: Display option value

var e = document.getElementById("country");
var result = e.options[e.selectedIndex].value;
alert(result); //ID002
Enter fullscreen mode Exit fullscreen mode

STEP 3: Display option text

var e = document.getElementById("country");
var result = e.options[e.selectedIndex].text;
alert(result); //United State
Enter fullscreen mode Exit fullscreen mode

STEP 4: JavaScript drop-down code

<!DOCTYPE html>
<html>
    <head>
        <title>JavaScript - Get selected value from dropdown list</title>
    </head>

    <body>

        <h1>JavaScript - Get selected value from dropdown list</h1>

        <p id="result">United State</p>

        <select id="country">
            <option value="None">-- Select --</option>
            <option value="ID001">China</option>
            <option value="ID002" selected>United State</option>
            <option value="ID003">Malaysia</option>
        </select>

        <script>

            function GetSelectedValue(){
                var e = document.getElementById("country");
                var result = e.options[e.selectedIndex].value;

                document.getElementById("result").innerHTML = result;
            }

            function GetSelectedText(){
                var e = document.getElementById("country");
                var result = e.options[e.selectedIndex].text;

                document.getElementById("result").innerHTML = result;
            }

        </script>

        <br/>
        <br/>
        <button type="button" onclick="GetSelectedValue()">Get Selected Value</button>

        <button type="button" onclick="GetSelectedText()">Get Selected Text</button>
    </body>

</html>
Enter fullscreen mode Exit fullscreen mode

Read more in original post

Discussion (0)

pic
Editor guide