JQuery validates dynamic percentage field

I am using jQuery validation plugin. I am trying to calculate the sum of all input fields using the .percent class. If the sum of the .percent fields is not 100%, perform a validation check.

The percentage of rows is part of the dynamic grid and can be very large. You will see an example of what I worked on below. I find addMethod is called for each input.percent, and not at a time. I would also like to say that it is called before the submit call.

the code.

HTML

<div class="row">
    <input value="" class="percent"/>
</div>
<div class="row">
    <input value="" class="percent"/>
</div>

Js

$.validator.addClassRules({
    percent: {percent:true}
});

$.validator.addMethod("percent",
    function cals(value, element) {
        // all the fields that start with 'coeff'
        var percent = element;
        var total = 0;
        for (var i = 0; i < percent.length; i++) {
            total += Number(percent[i].value);
        }
    return  total == 100;
}, $.format("Percentage fields most total up to 100%"));

$("form").validate({

});

Update

I tried the following code with little success

$("#modify-funding .percent").rules('add', {sum: 100});

$.validator.addMethod("sum", function (value, element, params) {
        var sumOfVals = 0;

        $("#modify-funding .percent").each(function () {
            sumOfVals = sumOfVals + parseInt($(this).val().length ? $(this).val() : 0);
        });
        if (sumOfVals == params) return true;
        return false;
    },
    $.format("Percentage fields most total up to 100%")
);

, . , .percent, 100% - .

2

, , . , , . , , , 100.

$("#modify-funding .percent").each(function() {
    $(this).rules('add', {sum: [".percent"]});
})

$.validator.addMethod("sum", function (value, element, params) {
    var sumOfVals = 0;
        $(params[0]).each(function() {
            sumOfVals += parseFloat($(this).val().length ? $(this).val() : 0);
        });

        if (sumOfVals == 100) return true;
        return false;
    },
    $.format("Percentage fields most total up to 100%")
);
+5
1

jquery . , jquery. .

    function validate() {
        var ret = false;
        var total = 0;
        var elems = document.getElementsByTagName('*'), i;
        for (i in elems) 
            if (elems[i].className == "percent") 
                total += parseFloat( elems[i].value);
        if (total == 100)
            ret = true;
        return ret;
    }
0

All Articles