TypeError: - is not a function

Viewed 611

I have this form which should hide another form:

  <!--checkbox-->
  <form method="POST" action="start.inc.php">
      <span id="switch"><!--these are for css, the input matters-->
          <label>
              <input id="hide" name="hide" type="checkbox" onclick="hide()" /><!--error here-->
              <span class="slider"></span>
          </label>
          <label for="hide">Do not set a password</label>
      </span>
  </form>

  <!--this should be hidden-->
  <form method="POST" action="start.inc.php">
      <!--form stuff-->
    <button type="submit" name="check">Set Password</button>
  </form>

So I implemented a function like this:

function hide() {
    var checkBox = document.getElementById("hide");
    var form =  document.getElementsByTagName("form")[1];

    if (checkBox.checked == true)
    {
        form.style.display = "none";
    } else {
        form.style.display = "block";
    }
}

It is written before the html, but even changing their order nothing changes...

The problem is that when I click on the checkbox the form doesn't disappear and I get the following error on the console: (index):93 Uncaught TypeError: hide is not a function at HTMLInputElement.onclick

Note: I'm a beginner in JS so please don't flame me if it was a stupid error

Thank you

1 Answers

The problem is that the name of the function is the same as the ID of the element. Element IDs become global variables, so hide is the <input> element rather than the function. The key to realizing this is that the error message doesn't say that hide is undefined, it says that it's not a function -- that means it's something else (in this case, a DOM element).

Give the function a name that's not the same as any element ID and it will work.

Related