0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.