submitHandler触发无效表单 - jQuery验证

时间:2014-09-23 17:32:12

标签: jquery jquery-validate

我有一个动态创建输入字段的表单。它工作得很好,但现在我需要在表单有效时调用函数。我的问题是,一旦表单加载submitHandler触发器。我通过在提交处理程序中添加alert("alert")来验证它。

 <input type="text" id="FName" name="FName" class = "vali" />   //these input fields are for demonstration; these are created dynmaiclly
 <input type="text" id="SName" name="SName" class = "vali"/>

 <button type="button" id="submit" name="submit">   //have tried type="submit" as well 
 </button>

 <script type="text/javascript">

  $(document).ready(function () {

        $('.vali').each(function () {
            $(this).rules('add', {
                required: true,
                messages: { required: "Can't be empty" },

                submitHandler: function (form) {
                    alert("alert"); // this fires as soon as the page load. 
                }
            })
        });
 });

 </script>  

1 个答案:

答案 0 :(得分:2)

submitHandler.validate()方法的回调函数(插件的初始化方法)。它是分配给整个表单行为的选项, 从不 分配给单个字段。

submitHandler ...

正确使用......

$(document).ready(function () {

    $('#myform').validate({ // initialize plugin
        submitHandler: function (form) {
            // fires on a VALID form just after the submit button click event. 
            alert("alert"); 
        }
    });

});

OR

$.validator.setDefaults({  // change default options
    submitHandler: function (form) {
        // fires on a VALID form just after the submit button click event. 
        alert("alert"); 
    }
});

由于需要在.setDefaults()之前调用.validate(),因此可以将其从DOM ready事件处理程序中拉出来强制执行此操作。

DEMO:http://jsfiddle.net/yvj202aL/