输入字段值“ undefined”,即使其中包含值

时间:2019-03-29 17:16:49

标签: javascript html gatsby

我正在尝试制作一个登录表格。出于某些原因,即使我填写表格并提交,我仍会输入错误“ null”或未定义

<form name ="loginform"  onSubmit ={validate()} method ="post">
      <p>Email</p>
    <input id = "mail"   type = "email"  name = "usr" placeholder = "Enter Email" required></input>
    <p>Password</p>
    <input id ="pass" type ="password"  name ="pword"  placeholder = "Enter Password" required></input>


     <input type = "submit"   name ="" value ="Login"  ></input> <br /> 
    <a id ="demo" href ="#" style={{color:'white'}} >Forget Password?</a><br />
    <a href = "#" style ={{color:'white'}}>need help?</a>
</form>




  function validate(){

  var un =document.getElementById("mail").value;
  var pw = document.getElementById("pass").value;

  var usernames = "username"; 
  var passwords = "password" ;
  if ((usernames ===  un) && (passwords === pw)) {
      window.location = " index.js ";
      return false;
  }
  else {
      alert ("Login was unsuccessful, please check your username and password");
  }
  } 

-这里是函数,但出现此错误:TypeError:无法获取未定义或空引用的属性“值”。任何帮助都已获得

1 个答案:

答案 0 :(得分:0)

尝试以下更改:

  1. 在您的var用户名中使用var usernames= "email@test.com";,因为您输入的是电子邮件。

  2. 虽然在每行上添加CSS样式都是不好的做法,但是您可以使用以下语法来做到这一点:style = "color:white"并添加,更改要更改的任何属性。 注意:白页上的白色文字会为您隐藏。

  3. 各种html错误,建议您每次在此处使用HTML代码进行测试: https://validator.w3.org/

这是我为您准备的最后文件:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1"> -->
    <!-- <link rel="stylesheet" type="text/css" media="screen" href="main.css"> -->
    <script>
        function validate() {
            var un = document.getElementById("mail").value;
            var pw = document.getElementById("pass").value;
            var usernames = "email@test.com";
            var passwords = "password";
            if ((usernames === un) && (passwords === pw)) {
                //window.location = " index.js ";
                //return false;
                alert("Login was Succesful"); // GOES HERE IF LOGIN WAS SUCCESSFUL
            }
            else {
                alert("Login was unsuccessful, please check your username and 
                      password");
            }
        } 
    </script>
</head>
<body>
    <form name="loginform" onSubmit={validate()} method="post">
        <p>Email</p>
        <input id="mail" type="email" name="usr" placeholder="Enter Email" required>
        <p>Password</p>
        <input id="pass" type="password" name="pword" placeholder="Enter Password" 
          required>
        <input type="submit" name="Login" value="Login"><br />
        <a id="demo" href="#" style="color: white">Forget Password?</a><br />
        <a href="#" style="color: white">need help?</a>
    </form>
</body>
</html>