如何在ajax请求返回的渲染表单上使用jquery.validate

时间:2012-01-11 16:01:49

标签: php jquery jquery-validate

使用jquery验证插件时遇到了一些问题。

它与正常页面加载期间呈现的静态表单完美配合。 我用于验证的代码看起来像这个

$('#form_name).validate({ (...) and other stuff

问题是,当我使用ajax请求创建具有相同ID的弹出窗体时,它将不起作用。

我找不到这个问题的正确答案,所以我来到这里。我想 $()。live 方法可能很有用,但我不知道如何在没有“click”,“submit”等事件的情况下使用它。

为了防止其他问题,加载新的ajax表单的页面位于除了呈现静态表单的页面之外的其他地方,因此在同一页面上没有两个相同表单的冲突。

1 个答案:

答案 0 :(得分:0)

我之前遇到过这个问题。新添加的ajax内容可能需要触发器重新初始化。您可以采取几种方法。以下只是其中之一。

将javasciprt绑定触发器放在一个函数中,并在ajax请求之后调用它。

<html>
<script type="text/javascript">

 // when page has loaded do the binds 
 $(document).ready(function(){
   initBinds();
 });

 // This is your ajax request psuedo code
 function someAjaxRequest(){

    // 1) do some ajax request then 
    // 2) load the data 
    // 3) after this has been done then call initBinds() 
          function to re-init new data with bind triggers
 }

function initBinds()    {
   $('#someID').bind('click', function(){
     // blah blah
   })


   $('#someOtherID').bind('click', function(){
     // blah blah
   })

}
</spript>

</html>