0

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.

3 Answers 3

3

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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!");
   }
}

Comments

0

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 ;)

1 Comment

console.log output only on console not on webpage. while user want to show the value on webpage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.