javascript 如何使用JS打印在HTML下拉框中选择的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22299023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:52:31 来源:igfitidea点击:
How to print the value selected in a drop-down box in HTML using JS
提问by jibs
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?
它显示一个下拉框,当我从框中选择一个值(比如参数 1)并单击“提交”时,我需要打印该值(在本例中为参数 1)。如何实现这一目标?
回答by lvil
var s = document.getElementsByName('parameters')[0];
var text = s.options[s.selectedIndex].text;
回答by Mr.G
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;
回答by vusan
Try this:
试试这个:
function myfunc() {
var par=document.getElementsByName('parameters')[0];
var index=par.selectedIndex
console.log(par.options[index].text);
}