jQuery验证未发生

问题描述 投票:0回答:1

我的页面上有这个脚本:

 <script type='text/javascript'>
    $(document).ready(function() {
        $('#TotalHours').attr('name', 'TotalHours'); // jQuery validation requires field names to be set

        $.validator.addMethod("hours", function(value, element) {
            var totalHours = 0;
            $('select').each(function(i, sel) {
                var hours = $(sel).find(":selected").text();
                if (hours != "")
                    totalHours += parseFloat(hours);
            });
            var reportedTotalHours = parseFloat($("#TotalHours").text());
            var difference = abs(totalHours - reportedTotalHours);
            return difference >= 0.25; // discrepancy must be less than a quarter hour
        });

        $('form').bind('submit', function() {
            $("#TheForm").validate({
                rules: {
                    TotalHours: {
                        hours: true
                    }
                }
            });
        });
    });
</script>

前几天我让它工作了,但是现在提交表单时,它没有经过验证(如果我在绑定到submit的函数中设置了一个断点,那么它将永远不会被命中)...我能得到什么坏了吗?

编辑:如果有帮助,这里是提交按钮的处理程序:

<script type='text/javascript'>
function __E374_onclick(){
    try{$("#TheForm").validate();
    if(!$("#TheForm").valid()){alert('The data you have entered is not valid. Please complete all required fields and correct any data entry errors.'); return;}
    var pm=$("#TheForm").serialize();$.post("/Action/Do/", pm, function(d){
        switch(true){
            case (null==d):dm("The server returned an unexpected response.");break;
            case (!d.Valid):case (!d.Successful):dm(d.Message);break;
            case (d.Successful):dm(d.Message);fu("EditAssessment");break;
            default:dm("An unexpected condition occurred.");break;}});
}catch(e){}}
</script>

和提交按钮本身:

<input type='button' id="__E374" class="button" value="Save" onclick="__E374_onclick();"/>
javascript jquery jquery-validate
1个回答
0
投票
$('form').bind('submit', function() {
    $("#TheForm").validate({
        ....

您不能将.validate()包装在提交处理程序中。该插件已经可以自动捕获Submit事件,因此这毫无意义。并阻止插件在表单上初始化自身,直到第一个Submit事件。 (BTW-jQuery .bind()已弃用)

[.validate()方法用于初始化表单上的插件,并在表单创建后调用,通常是在ready事件处理程序中。

<input type='button' ....

该插件将忽略来自<button>type="button"的点击。您需要将其更改为type="submit"

请参考the SO Wiki page了解典型用法和示例。

© www.soinside.com 2019 - 2024. All rights reserved.