且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JQuery验证:如何添加验证它检查多个字段的总和?

更新时间:2023-11-09 20:36:40

 <脚本>
$(文件)。就绪(函数(){
    $(#某种形式的)。验证({        规则:{
            TextBox1的:{
                要求:真实,
                编号:真,
                分:0,
                最大:100,
            },
            TextBox2中:{
                要求:真实,
                编号:真,
                分:0,
                最大:100,
            }
            TextBox3:{
                要求:真实,
                编号:真,
                分:0,
                最大:100,
            }
            TextBox4:{
                要求:真实,
                编号:真,
                分:0,
                最大:100,
            }        },
        submitHandler:功能(形式){
            无功总= parseInt函数($(#TextBox1中)。VAL())+ parseInt函数($(#TextBox2中)。VAL())+ parseInt函数($(#TextBox3)。VAL())+ parseInt函数( $(#TextBox4)VAL())。
            如果(总!= 100){
                $(错误)。HTML(你总总和必须100。)
                返回false;
            }其他form.submit();
        }    });
});< / SCRIPT>

被盗和编辑from这里。

I'm trying to use jQuery validation for a dynamic form I'm setting up.

In some cases this form contains a set of input boxes which are suppose to total 100.

An example might be:

Please indicate what percentage of students are in each grade?
Grade 9: TextBox1
Grade 10: TextBox2
Grade 11: TextBox3
Grade 12: TextBox4

I want to verify that TextBox1 + TextBox2 + TextBox3 + TextBox4 = 100%.

How do I go about this?

Thanks!

<script>
$(document).ready(function(){
    $("#some-form").validate({

        rules: {
            TextBox1: {
                required: true,
                number: true,
                min: 0,
                max: 100,
            },
            TextBox2 : {
                required: true,
                number: true,
                min: 0,
                max: 100,
            }
            TextBox3 : {
                required: true,
                number: true,
                min: 0,
                max: 100,
            }
            TextBox4 : {
                required: true,
                number: true,
                min: 0,
                max: 100,
            }

        },
        submitHandler: function(form){
            var total = parseInt($("#TextBox1").val()) + parseInt($("#TextBox2").val()) + parseInt($("#TextBox3").val()) + parseInt($("#TextBox4").val());
            if (total != 100) {
                $(".error").html("Your total must sum to 100.")
                return false;
            } else form.submit();
        }

    });
});

</script>

Stolen and edited from here.