最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to use the if statement (JavaScript) with the select tag in HTML? - Stack Overflow

programmeradmin1浏览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.

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.

Share Improve this question edited Sep 20, 2015 at 11:24 Thomas Bormans 5,3727 gold badges37 silver badges51 bronze badges asked Sep 20, 2015 at 10:50 user4748521user4748521
Add a ment  | 

3 Answers 3

Reset to default 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/snsbbytw/

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

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

发布评论

评论列表(0)

  1. 暂无评论