2013-06-04 64 views
1

fancybox和jquery验证插件时,表单处于fancybox容器时出现问题。fancybox和jquery表单验证

对于examle(在线): HTML:

<script> 
$(document).ready(function(){ $.fancybox(' 
<form class="myform"> 
<input type="text" name="email" class="email" /> 

<input type="submit" value="submit" name="submit" /> 
</form> 
'); 
}) 
</script> 

js文件:

$(".myform").validate(
      { 
      rules: { 
      email: "required", 
      email: "email" 
       } 
      } 
     ); 

如何让jQuery验证pluging中的fancybox工作?

+0

您必须使用'.validate()'_after_的'form'是创建。 – Sparky

+0

你可以在fancybox的'beforeShow'回调中初始化验证插件 – JFK

+0

@JFK,我不认为'beforeShow'可以工作。 'form'必须在调用'.validate()'之前构造。 afterLoad更合适。 – Sparky

回答

4

做两件事情......

  1. 使用afterLoad的fancybox回调函数初始化.validate()形式加载之后。

  2. 将FancyBox的内容置于隐藏的div而不是您的jQuery中。它更干净。

注意:您可能需要使用emailname属性重新考虑。由于该规则也被称为email,因此它可能引起很大的混淆。

HTML

<a id="test" href="#inline">Test</a> 

<div style="display:none" id="inline"> 
    <form class="myform"> 
     <input type="text" name="email" class="email" /> 
     <input type="submit" value="submit" name="submit" /> 
    </form> 
</div> 

jQuery的

$(document).ready(function() { 

    $('#test').fancybox({ 
     afterLoad: function() { 
      $('.myform').validate({ 
       // rules and options for validate plugin, 
       rules: { 
        email: { // "email" is name of the field 
         required: true, 
         email: true // "email" is name of the rule 
        } 
       } 
      }); 
     } 
    }); 

}); 

工作演示:http://jsfiddle.net/ZMEEW/

+0

你总是可以使用'beforeShow',因为表单已经构建好了,不可见,尽管 – JFK

+0

@JFK,好的,使用其中一个。随你。 – Sparky