2014-10-09 50 views
0

忽略我花了一个小时工作,所以我会沮丧,事实证明它只是一个单引号错误的地方或什么的。退回false由onsubmit

我正在做一个基本的HTML页面来测试一个基本的验证表单输入。如果我在validateForm()函数的开始处放弃返回false,它将按预期工作。但是,如果它在验证循环中(如下所示),它不起作用并且表单提交。 (hello.php只是输出hello world)。

这里所有的诊断警报按预期方式运行......包括在返回false之前的那一个。 (当我离开输入空白)。

我觉得我失去了一些非常明显的东西,但不知道它是什么。

<?php 
echo <<<END 
<html> 
<head> 
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script> 
    <title>Test</title> 

    <script type="text/javascript"> 
$(document).ready(function(){ 
    $("input").focus(function(){ 
    $(this).css("background-color","#cccccc"); 
    }); 
    $("input").blur(function(){ 
     $(this).css("background-color","#ffffff"); 
    }); 
}); 

function validateForm() { 
    alert("Validating");  
    $("form[name=queryForm]").find(":input[type=text]").each(function() { 
     alert("Checking " + $(this).attr('name')); 
     if($(this).val()==null || $(this).val()=="") { 
      $(this).val('REQUIRED'); 
      $(this).css("background-color","#ffbbbb"); 
      alert($(this).attr('name') + ' must not be left blank.'); 
      return false; 
     } 
    }); // end of the each function 
} 
</script> 
</head> 
<body> 
<form name="queryForm" action="hello.php" onsubmit="return validateForm();" method="post"> 
<input type="text" name="First Name"><br> 
<input type="text" name="Last Name"> 
<input type="submit" value="Submit"> 
</form> 
</body> 
</html> 
END; 
?> 

回答

1

使用收益以外的变量()获没有你想要的结果。

试试这个:

function validateForm() { 
alert("Validating");  
var result = true; 
    $("form[name=queryForm]").find(":input[type=text]").each(function() { 
    alert("Checking " + $(this).attr('name')); 
    if($(this).val()==null || $(this).val()=="") { 
     $(this).val('REQUIRED'); 
     $(this).css("background-color","#ffbbbb"); 
     alert($(this).attr('name') + ' must not be left blank.'); 
     result =false; 
     return false; //break the each() 
    } 
}); // end of the each function 
return result; 
} 
+0

设置一个varible,并将它作为我的“端”功能之外回报工作。 但是为什么? “使用return insidw .each()不会得到您想要的结果。”为什么不? 谢谢...... – lowcrawler 2014-10-10 00:59:07

+0

@lowcrawler return()里面的each()会调用each()的回调函数。返回虚假将打破每个。 – 2014-10-10 15:29:48

1
find(":input[type=text]") 

应该

find("input[type=text]") 

你也可能要返回时设置insidw的。每次的.each

function validateForm() { 
    var valid = true; 
    alert("Validating");  
    $("form[name=queryForm]").find(":input[type=text]").each(function() { 
     alert("Checking " + $(this).attr('name')); 
     if($(this).val()==null || $(this).val()=="") { 
      $(this).val('REQUIRED'); 
      $(this).css("background-color","#ffbbbb"); 
      alert($(this).attr('name') + ' must not be left blank.'); 
      valid = false; 
     } 
    }); // end of the each function 
    //then return that variable 
    return valid; 
}