views:

43

answers:

1

I have a bunch of fields like so created on the fly

<input type="text" name="coeff_a">
<input type="text" name="coeff_b">
<input type="text" name="coeff_c"> .. and so on ..

I want to validate the input to the above fields, and am using the jQuery validate plugin. I have set up a rule like so

jQuery.validator.addMethod(
    "perc",
    function(value, element) {
        // all the fields that start with 'coeff'
        var coeff = $("input[name^='coeff']");
        var total;

        for (var i = 0; i < coeff.length; i++) {
            total += coeff[i].value;
        }

        if (total <= 100) {
            return true;
        }

        return false;
    }, 
    jQuery.format("Please ensure percentages don't add up to more than 100")
);

Needless to say, the above is not working. Any ideas what I am doing wrong?

+1  A: 

Your function is not returning correct value.

function cals(value, element) {
    // all the fields that start with 'coeff'
    var coeff = $("input[name^='coeff']");
    var total = 0;
    for (var i = 0; i < coeff.length; i++) {
        total += Number(coeff[i].value);
    }

    if (total <= 100) {
        return true;
    }

    return false;
}

Edited something. Give it a look.

simplyharsh
yes! that did it! Thanks.
punkish