2014-02-28 53 views
0

起初,我有这个和它的工作完美,但它提交即使有错误:为什么我的表单即使出现错误也会提交?

$(document).ready(function(){ 
     $('input[name=subdomain]').keyup(subdomain_check); 
     $('input[name=password]').keyup(password_strenght); 
     $('input[name=c_password]').keyup(password_check); 
     $('input[name=email]').keyup(email_check); 
    }); 

所以我改成这样了,现在它不调用内部的功能!

$(document).submit(function(e){ 
    $('input[name=subdomain]').keyup(subdomain_check); 
    $('input[name=password]').keyup(password_strenght); 
    $('input[name=c_password]').keyup(password_check); 
    $('input[name=email]').keyup(email_check); 
    return false; 
}); 

这里有什么问题?
这是整个代码:http://pastie.org/8812743

+1

删除'返回false;' – Ani

+4

我认为这个问题需要进一步澄清。 –

+0

这里的信息不够充分。定义什么行不通,你可能得到的任何错误,这些功能的定义以及如何。那么也许有人可以帮助你。还返回假;会导致提交功能无法执行。 – scrappedcola

回答

1

你是不是安装了KEYUP事件处理程序直到发生提交事件。此时用户已经完成了所有字段的输入。

将呼叫转移到$(...).keyup(...)回到dom ready事件。实际上,你需要一个额外事件处理程序来检查用户输入:

$(document) 
    .ready(function(){ 
     $('input[name=subdomain]').keyup(subdomain_check); 
     $('input[name=password]').keyup(password_strenght); 
     $('input[name=c_password]').keyup(password_check); 
     $('input[name=email]').keyup(email_check); 
    }) 
    .submit(function(e) { 
     // validate input 
     // if invalid, show error message and call e.preventDefault(); 
    }); 

一般用户的工作流程是:

  1. jQuery中的domready事件被调用时,附加keyup事件处理程序
  2. 的用户键入表单域,触发键盘处理程序
  3. 用户提交表单,触发提交处理程序
  4. 提交处理程序验证表单输入,如果无效,则向用户显示错误消息并阻止提交事件继续。
0

不知道到底是什么你的验证函数返回,但如果它是一个布尔值,你可以,也许只是做这样的事情:

$("#formId").submit(function(e){ 
    if(!subdomain_check() || !password_strenght() || !password_check() || !email_check()) { 
     e.preventDefault(); 
    } 
}); 
+1

我认为这个答案指向了正确的方向。然而,你可能想纠正一些问题:它应该是'$('#formId')。submit(...)',你应该调用if语句中的函数,例如'subdomain_check()',等等 – Steve

+0

你对,编辑。 – MamaWalter

0
$(document).ready(function(){ 
     $('input[name=subdomain]').keyup(subdomain_check); 
     $('input[name=password]').keyup(password_strenght); 
     $('input[name=c_password]').keyup(password_check); 
     $('input[name=email]').keyup(email_check); 

     function subdomain_check (e) { 
     // these functions should set a global variable to false if validation fails 
     } 

     function password_strenght (e) { 
     // these functions should set a global variable to false if validation fails 
     } 

     function password_check (e) { 
     // these functions should set a global variable to false if validation fails 
     } 

     function email_check (e) { 
     // these functions should set a global variable to false if validation fails 
     } 

     $(document).submit(function(e){ 
      return global_var; // where global_var is the variable set by the validating functions 
     } 

    }); 
相关问题