正在重新加载HTML表单并且不显示java脚本消息

时间:2015-07-08 17:05:16

标签: javascript html html5

我是Javascript编程的新手。我开发了以下脚本并遇到以下问题。请专家帮助解决问题。

问题是

  • 当填写用户名和密码(用户名不等于密码)时,将显示javascript消息,表单会自动重新加载删除消息。
  • 当用户名或密码为空时,显示的消息为"无效的用户名或密码"。没有显示正确的javascript消息。
  • 当两个字段都未填满时,脚本会成功执行,并且#34;欢迎"打印出来。如果javascript中的条件没有被执行则显示正确的消息。也使用了" required"属性显示错误"该字段是必需的"但仍然欢迎'正在印刷。



    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function verify() {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    if ((typeof username) == undefined) {
        document.getElementById("message").innerHTML = "Username Required.";
    }
    
    if ((typeof password) == undefined) {
        document.getElementById("message").innerHTML = "password Required.";
    }
    
     if (username == password) {
        document.write("Welcome");
        }
     else {
        document.getElementById("message").innerHTML = "Invalid Username or password";
        }
    }
      
    </script>
    </head>
    <body>
    
    <h1 style="text-align:center">Welcome to MEPC World!!</h1>
    <br>
    <form style="margin:auto;max-width:60%" >
    <fieldset style="border:groove;border-width:5px;border-color:lightgrey;text-align:center">
    <legend><b>Login</b></legend>
      <p id="message" style="color:red;text-align:left"></p>
      <br>
      Username&nbsp;:&nbsp;
      <input id="username" type="text" placeholder="username (e.g. XYZ)" autocomplete="off" required="required"> </input>
      <br>
      <br>
      Password&nbsp;&nbsp;:&nbsp;
      <input id="password" type="password" placeholder="password" required="required"> </input>
      <br><br>
      <input type="submit" value="Submit" onclick="verify()">
    </fieldset>
    </form>
    
    <p><b>Note:</b> Username and password are case-sensitive.</p>
    
    </body>
    </html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

这就是你应该这样做的方式。或者邮件被覆盖,因为您有多个if语句而不是if/elseif/else语句,只允许一个语句true

function verify() {
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;

  if (username === undefined || username === '') {
    document.getElementById("message").innerHTML = "Username Required.";
  }

  else if (password == undefined || password === '') {
    document.getElementById("message").innerHTML = "password Required.";
  }
  // This doesn't make sense at all fyi
  else if (username === password) {
    document.write("Welcome");
  }
  else {
    document.getElementById("message").innerHTML = "Invalid Username or password";
  }
}

要阻止表单提交,您必须执行此操作:

<input type="submit" value="Submit" onclick="return verify()">