简体   繁体   中英

How to print the value selected in a drop-down box in HTML using JS

I am designing a web page which goes like this:

<html>
<head>
<title>Bug UI</title>
</head>

<body>

<script>
    function myfunc()
    {
    //what goes here??
    }
</script>
<form>
    <select name = "parameters">
        <option value = "param1">Param 1</option>
        <option value = "param2">Param 2</option>
        <option value = "param3">Param 3</option>
        <option value = "param4">Param 4</option>
        <option value = "param5">Param 5</option>
    </select>
    <input type = "button" onclick = "myfunc()" value = "Submit">
</form>
</body>
</html>

It displays a drop-down box, when I select a value (say Param 1) from the box and click "Submit", I need to print the value (Param 1 in this case). How to achieve this?

var s = document.getElementsByName('parameters')[0];
var text = s.options[s.selectedIndex].text;

try this work perfectly:

var ex = document.getElementsByTagName('select');
var str= ex.options[ex.selectedIndex].value;
 **or**
var str= ex.options[ex.selectedIndex].text;

or

var ex = document.getElementsByName('parameters')[0];
var str= ex.options[ex.selectedIndex].value;
      **or**
var str= ex.options[ex.selectedIndex].text;

Try this:

function myfunc() {
   var par=document.getElementsByName('parameters')[0];
   var index=par.selectedIndex
   console.log(par.options[index].text);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM