Reputation:
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.
Upvotes: 0
Views: 21734
Reputation: 13763
You are probably looking for the onChange event
<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 ;)
Upvotes: 0
Reputation: 5501
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/
Upvotes: 3
Reputation: 1395
I guess you have to listen to the change event of the select.
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!");
}
}
Upvotes: 0