Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery validate: sum of multiple input values

I need help to create custom method to validate sum of multiple text input values.

In form I have variable number of text inputs and when submitting I need to validate that the sum of input values in same group is exactly 100.

example (second group should not validate):

<input type='text' name='g1_number1' class='group1' value='20' />
<input type='text' name='g1_number2' class='group1' value='40' />
<input type='text' name='g1_number3' class='group1' value='40' />

<input type='text' name='g2_number1' class='group2' value='20' />
<input type='text' name='g2_number2' class='group2' value='40' />
<input type='text' name='g2_number3' class='group2' value='10' />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I got it working this way:

Custom validation rule:

$.validator.addMethod(
    "sum",
    function (value, element, params) {
        var sumOfVals = 0;
        var parent = $(element).parent(".parentDiv");
        $(parent).find("input").each(function () {
            sumOfVals = sumOfVals + parseInt($(this).val(), 10);
        });
        if (sumOfVals == params) return true;
        return false;
    },
    jQuery.format("Sum must be {0}")
);

And using like this:

$(".group1").rules('add', {sum: 100});
$(".group2").rules('add', {sum: 100});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...