简体   繁体   English

表单输入,需要帮助设置输入值

[英]Form input, need help setting value of input

i'm trying to get value of input field, so depending on if the input value is 0 or 1, the value of the input is one or two, and it's supposed to show up in console.我正在尝试获取输入字段的值,因此根据输入值是 0 还是 1,输入的值是一或二,它应该显示在控制台中。

<!DOCTYPE html>
<html lang="en-US">

<head>
    <title>demo</title>
    <meta charset="utf-8">
    <style>

    </style>
</head>

<body>
    <p>Input 0 or 1.</p>
    <input id="ok" type="text">
    <button onclick="functionn()"></button>
    <script>
          var x = document.getElementById("ok").value;

        function functionn() {
            if (x == 0) {
                ok = "one";
                console.log(ok); }
             else if (x == 1) {
                ok = "two";
                console.log(ok);

            } else {
                alert("please input 0 or 1");
            }
        }

    </script>

</body>

</html

You are so close!你离得那么近!

The problem that you have is the "x" variable, it holds the value on the input after the page was loaded, which is and empty string.您遇到的问题是“x”变量,它保存页面加载后输入的值,即空字符串。

You need to put that variable inside the function, so every time you click the button you will "go" and check the value of the input and then store it inside the "x" variable.您需要将该变量放入函数中,因此每次单击按钮时,您都会“转到”并检查输入的值,然后将其存储在“x”变量中。

Hope this help!希望这有帮助! =] =]

try it:尝试一下:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>demo</title>
        <meta charset="utf-8" />
        <style></style>
    </head>

    <body>
        <p>Input 0 or 1.</p>
        <input id="ok" type="text" />
        <button onclick="functionn()"></button>
        <script>
            var x = document.getElementById("ok");

            function functionn() {
                if (x.value === "0") {
                    ok = "one";
                    console.log(ok);
                } else if (x.value === "1") {
                    ok = "two";
                    console.log(ok);
                } else {
                    alert("please input 0 or 1");
                }
            }
        </script>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM