Voldemort's Wrath
Voldemort's Wrath

Reputation: 91

Why isn't it checking for the correct value? (Javascript/HTML)

Here is my code:

<html>
<body>
<script type="text/javascript">
function CheckPwd()
{
 if(document.forms['frm'].pass.value == "magicisreal")
    {
      alert('Welcome, ADMIN...');
      return true;
    }
      return false;
}
</script>

Password:
<br>
<input type="password" name="pass">
<br><br>
<input type="submit" value="Continue" onclick="return CheckPwd()">

</body>
</html>

It is supposed to return an alert when the value "magicisreal" is entered into the textbox. What, exactly, am I doing wrong that is not causing this result?

Upvotes: 1

Views: 46

Answers (3)

Amit Baranes
Amit Baranes

Reputation: 8132

First of all,there is no form named frm. So, the if statement you are checking is not valid. use the following code snippet to achieve what you are looking for :

<html>
<body>
<script type="text/javascript">
function CheckPwd()
{
var password = document.getElementById('pass-input').value;
console.log(password);
 if(password == "magicisreal")
    {
      alert('Welcome, ADMIN...');
      return true;
    }
      return false;
}
</script>

Password:
<br>
<input type="password"  id="pass-input" name="pass">
<br><br>
<input type="submit" value="Continue"  onclick="CheckPwd()">

</body>
</html>

Upvotes: 1

Sami Ahmed Siddiqui
Sami Ahmed Siddiqui

Reputation: 2386

You are using document.forms which expects that form exists in your HTML but you have not defined that. Just define the HTML form either with name=frm.

function CheckPwd() {
    if(document.forms["frm"].pass.value == "magicisreal") {
        alert('Welcome, ADMIN...');
        return true;
    }

    return false;
}
<html>
    <body>
    <form name="frm" action="">
    Password:
    <br>
    <input type="password" name="pass">
    <br><br>
    <input type="submit" value="Continue" onclick="return CheckPwd()">
    </form>
    </body>
 </html>

Upvotes: 0

Matti Bar-Zeev
Matti Bar-Zeev

Reputation: 106

You are missing the Form. Try this -

<script type="text/javascript">
  function CheckPwd() {
    if (document.forms['frm'].pass.value == "magicisreal") {
      alert('Welcome, ADMIN...');
      return true;
    }
    return false;
  }
</script>

Password:
<br>
<form name="frm">
  <input type="password" name="pass">
  <br><br>
  <input type="submit" value="Continue" onclick="return CheckPwd()">
</form>

Upvotes: 0

Related Questions