Jquery.validate: multiple fields add to value

I am working on a form in which the user enters a total number, and then enters more values ​​into other fields, which are a division of this amount. For instance:

<input type="text" name="total" /> <input type="text" name="portion[1]" /> <input type="text" name="portion[2]" /> <!-- and so on --> <input type="text" name="portion[n]" /> 

If the user enters the total number 123.45, then parts 1 - n must be filled in so that their values ​​are up to 123.45. The field of each section must be a positive number or 0, but these are the only other restrictions on them.

The jquery.validate plugin has an equalTo validation method, but it might seem like it only handles one field, not a set.

Is there any way

  • Define a validation rule that will check the total number of field groups against the common field
  • Get a separate message for a group of fields if they do not add up
+4
source share
3 answers

This question looks like it has some answers that may be useful in solving this problem.

0
source

Try this function with jquery event

  function Mvalidate() { var total=$('[name=total]').val(); var n=10; // no of portions var partialsum=0; for(var i=0;i<n; i++) { var t=$("[name=portion["+i+"]]").val(); partialsum+=parseFloat(t); } if(partialsum<total) alert("Portions add up not complete!"); } $("#checkbutton").click(function() { Mvalidate(); }); 
+1
source

@Krishnan:

according to jquery doc

$ ('General').

is a class selector, isn't it? If you want to find an element with a name attribute, you must write it as follows:

 $("[name='total']").val(); $("[name='portion["+i+"]']").val(); 

If you know that there is only an input field with this name, you can use

 $("input[name='total']").val(); 
0
source

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


All Articles