-5

It's fixed now.

It's basically a textbox that when the right text is entered should cause something to happen, i have code for it, this is my first time playing around with html. It's not really for anything and just for fun

<body>
    <center>
        <input id="passfield" type="text" value="" />
        <input id="check" type="button" value="Check" onclick="check();"/>
        <script>
            var field = document.getElementById("passfield").value;
            var pass = "password";
            function check() {
                if field === pass then {
                    window.location.href = 'the site i want it to go to';
                }; 
            };
            document.getElementById("check").onclick = check();
        </script>
    <center>
</body>

The console says: check() isn't a function

1 Answers1

2

You have a couple problems:

  • You should move the variables field and pass into the function, so that they're defined when the function is called. Otherwise, they won't update - which means field will always be empty (since it was set as soon as the page loaded, when the input's value was '')

  • Add an event listener in your Javascript, rather than using the 'onclick' attribute. It's nicer because it keeps all of your Javascript together, and you won't have to skim through your HTML every time you hit a JS error.

You have some formatting issues - the if in particular should use the following syntax:

if (condition) {
 then do this
} else {
  do this
}

You can check out this example on CodePen.

<body>
  <center>
    <input id="passfield" type="text" value="" />
    <input id="check" type="button" value="Check" />
    <center>
      <script>
        function check() {
          var field = document.getElementById("passfield").value;
          var pass = "password";
          if (field === pass) {
            window.location.href = "the site i want it to go to";
          }
        }
        document.getElementById("check").addEventListener('click', check)
      </script>
</body>
Bricky
  • 2,572
  • 14
  • 30
  • Your first point is wrong, they are declared as global variables and check function can use them, it's not a good practice because is in the global scope so take much time to access them – Kalamarico Oct 04 '17 at 22:14
  • 1
    It's not wrong. With the way his code is written the value for field is never updated, but instantly initialized to an empty string. Worrying about speed and global scope is clearly not relevant to someone at this stage of learning. – Bricky Oct 04 '17 at 22:18
  • The problem was with field var because it needs to take the document... value in onclick, but password no, you are wrong referring to both variables in your first point. I agree with you with the last part of the comment, but answers and questions are for everyone. And the question in fact is "why check isn't a function", only due to the if error syntax – Kalamarico Oct 04 '17 at 22:19