0

这是我保存为 n_form.html 的登录表单。我正在尝试检查空字段,但是每当我单击登录而不填写字段时,我的表单都会重定向到下一页而不是发送消息。请帮忙。

<!DOCTYPE html>
<html>
  <head>
  <title>Registration Form Of Teknack</title>
  <link rel="stylesheet" type="text/css" media="screen" href="css-page.css" />
  <script language="Javascript">
      function validateForm(){
         var x=document.forms["n_form"]["Username"].value;
         var y=document.forms["n_form"]["Password"].value;
         if (x==null || x=="" & y==null || y==" "){
               alert("Form must be filled.");
               return false;
         }
     }
  </script>
  </head>
  <body>
     <br><br><br>
     <form name="n_form" action="form.php"  onclick="return validateForm()"        method="post">      
     <ol>
        <li>Username<br> 
            <input id="width" type="text" name="name" value="" /></li>
    <li><br>Password<br>
        <input id="width" type="password" name="password" value="" /></li>
        <li><br>
            <input type="checkbox" value="">Remember me<br></li>
        <li id="login">
        <br><button type="submit">Login</button></li>
     </ol>
     </form>
  </body>
</html>

提前致谢,

4

2 回答 2

1

尝试:

function validateForm()
{
var x=document.n_form.name.value;
var y=document.n_form.password.value;
 if (x==null || x=="" && y==null || y=="")
 {
alert("Form must be filled.");
return false;
  }
 }

DEMO FIDDLE

于 2013-09-07T10:18:30.190 回答
1

我强烈建议使用 jQuery 而不是 Javascript!获取并学习。然而,这是答案:

jQuery 验证和表单的教程演示:http: //speckyboy.com/2009/12/17/10-useful-jquery-form-validation-techniques-and-tutorials-2/

Javascript中的解决方案:

Javascript代码:

<script language="javascript">
function validateForm(form)
{
 var username=getElementbyId('username').value;
 var password=getElementbyId('password').value;
 if(username == "")
 {
   alert("You must fill up username!");
 }
 else if (password == "")
 {
   alert("You must fill up password!");
 }
 else
 {
   // nothing, okay status...
 }

     // or if you want to show a message on one of empty field:

 if (username == "" || password == "")
 {
   alert("You must fill up a form");
 }
 else
 {
   // nothing, okay status...
 }


}

并在 HTML FORM 中进行更改:

<li>Username<br>
    <input id="username" type="text" name="username" value="" />
</li>


<li><br>Password<br>
    <input id="password" type="password" name="password" value="" />
</li>

<li><br><input type="checkbox" value="">Remember me<br>
</li>


<li id="login">
    <br><button type="button" onclick="check(this.form)">Login</button>
</li>
于 2013-09-07T10:20:00.267 回答