Kai
Kai

Reputation: 47

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.

<!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

Upvotes: 0

Views: 72

Answers (2)

maryam
maryam

Reputation: 161

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>

Upvotes: 1

Buttered_Toast
Buttered_Toast

Reputation: 991

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.

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.

Hope this help! =]

Upvotes: 1

Related Questions