[英]How to use the if statement (JavaScript) with the select tag in HTML?
I've tried many ways to do this but this isn't right: 我尝试了很多方法来做到这一点,但这是不对的:
<html>
<head>
<title>Select</title>
</head>
<body>
<select name="test">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<script>
if (test=="two") {
document.write("two!");
}
</script>
</body>
</html>
I want to let something appear on the screen if the user chooses "two" but this doesn't work. 如果用户选择“两个”,我想让某些东西出现在屏幕上,但这是行不通的。
I think this might help you 我认为这可能对您有帮助
<select name="test" id="mySelect" onchange="myFunction()">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
if(x == "two"){
document.getElementById("demo").innerHTML = "You selected: " + x;
}
}
</script>
Have a look http://jsfiddle.net/snsbbytw/ 看看http://jsfiddle.net/snsbbytw/
I guess you have to listen to the change event of the select. 我猜您必须听听select的change事件。
document.getElementsByName("test")[0].addEventListener("change", function(e) {
if (e.target.value === "two") { // not sure if it's e.targe.value, and this might not work in all browsers
document.write("two!");
}
}
You are probably looking for the onChange event 您可能正在寻找onChange事件
<select name="test" onchange="console.log(this.value)">
Avoid using document.write since it will replace the document output.. And of course, avoid use inline scripting ;) 避免使用document.write,因为它将替换文档输出。当然,请避免使用内联脚本;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.