JQuery Validate: How to add a validation that checks the sum of multiple fields?

I am trying to use jQuery validation for a dynamic form that I am customizing.

In some cases, this form contains a set of input boxes, which are assumed to be 100.

An example could be:

Please indicate what percentage of students in each class?
Grade 9: TextBox1
Grade 10: TextBox2
Class 11: TextBox3
Class 12: TextBox4

I want to check that TextBox1 + TextBox2 + TextBox3 + TextBox4 = 100%.

How can I do it?

Thanks!

+3
source share
1 answer
<script> $(document).ready(function(){ $("#some-form").validate({ rules: { TextBox1: { required: true, number: true, min: 0, max: 100, }, TextBox2 : { required: true, number: true, min: 0, max: 100, } TextBox3 : { required: true, number: true, min: 0, max: 100, } TextBox4 : { required: true, number: true, min: 0, max: 100, } }, submitHandler: function(form){ var total = parseInt($("#TextBox1").val()) + parseInt($("#TextBox2").val()) + parseInt($("#TextBox3").val()) + parseInt($("#TextBox4").val()); if (total != 100) { $(".error").html("Your total must sum to 100.") return false; } else form.submit(); } }); }); </script> 

Stolen and edited here .

+6
source

Source: https://habr.com/ru/post/1341106/


All Articles