Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' />
like image 543
Vertigo Avatar asked Nov 19 '10 12:11

Vertigo


2 Answers

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});
like image 150
Vertigo Avatar answered Nov 07 '22 15:11

Vertigo


var sumOfValues=0;
$(".group1").each(function(){
   sumOfValues+=$(this).val();
});
if(sumOfValues==100){

}else{

}

or in plugin form

$.fn.validateValuesSum=function(value){
   var sumOfValues=0;
   this.each(function(){
     sumOfValues+=$(this).val();
   });
   if(sumOfValues==value){
      return true;
   }
   return false;
}
like image 25
rterrani Avatar answered Nov 07 '22 14:11

rterrani