返回虚假后仍然提交表格

时间:2014-01-14 18:10:09

标签: javascript jquery

我添加了验证,但即使脚本返回false

,表单仍然会提交

表格提交

 <form action=payment.php method=POST name=UserForm id=UserForm onsubmit="return check(this);return false;">    

Javascript

 function check(event) {    

 $('input').each(function() {
    if(!$(this).val()){
        alert('Some fields are empty');
       return false;
    }
   });  


   } 

2 个答案:

答案 0 :(得分:4)

jQuery return false;中的

each将无效。您将在匿名函数内返回,而不是在function check(event)内。 你需要做的是使用旗帜。

function check(event) {  
    var errorFlag = false;
    $('input').each(function() {

        if(!$(this).val()){
            alert('Some fields are empty');
            errorFlag = true;
        }

    }); 

    return !errorFlag;
}

答案 1 :(得分:0)

return check(this);return false;

第二次返回return false无法访问。此外,alert语句会阻止其他代码中的返回 - 而check函数不会返回任何内容。

function check(event) {    
 $('input').each(function() {
    if(!$(this).val()){
       alert('Some fields are empty'); //blocking here
       return false; // this isn't the return of the check function
    }
   });  
}

您应该执行类似

的操作

function check(event) {    
   var result = true;
   $('input').each(function() {
    if(!$(this).val()){
       result = false;
    }
   });  

   return result;
}
相关问题