Get value of variable inside .each() function jQuery

Viewed 291

I have code below.

The code works fine, but if I uncomment the "if" statement, alert will show up as soon as I enter something to input field.

I want the "sum" value to be checked (alert shows up) only after I entered all 3 input fields.

Please help me to fix it. Thanks.

<apex:inputField styleClass="Weight" value="{!EvaluationInformation__c.val1__c}" />
<apex:inputField styleClass="Weight" value="{!EvaluationInformation__c.val2__c}" />
<apex:inputField styleClass="Weight" value="{!EvaluationInformation__c.val3__c}" />
$(document).ready(function() {
  $(document).on("input", ".Weight", function(e) {
    var sum = 0;
    $('.Weight').each(function() {
      var num = $(this).val();
      if (num != null && !isNaN(num)) {
        sum += parseFloat(num);
      } else {
        alert("Accept number only");
      }
    });

    //if (sum != 1){ // sum !=1 doesn't work
    //  alert("The total of Weight must be 1");
    //} 
  });
});
1 Answers

You can use a status flag that will tell if all inputs are valid, see my example code below.

Also, AFAIK val() for an <input> element never returns null, it returns "" if there is no input. This is why I used if (num && ... instead, which in this situation means "only proceed if num contains text".

$(document).ready(function() {
  $(document).on("change", ".Weight", function(e) {
    var sum = 0;
    var allInputsValid = true; // <-- flag variable
    $('.Weight').each(function() {
      var num = $(this).val();
      if (num && !isNaN(num)) {
        sum += parseFloat(num);
      } else {
        allInputsValid = false;
      }
    });
    if (allInputsValid) {
      console.log("All inputs have numbers.");
      if (sum != 1) {
        console.log("The total of Weight must be 1, but it is: " + sum);
      } else {
        console.log("The total of Weight is 1.");
      }
    } else {
      console.log("Not all input have numbers yet.");
    }
  });
});
.Weight { width: 50px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
#1: <input class="Weight" /> #2: <input class="Weight" /> #3: <input class="Weight" />


PS - Even then, you may have trouble making this work because of how Floating Point math works. Due to internal rounding, a sum of numbers that you would expect to be 1 will not always produce exactly 1:

var x = parseFloat("0.34") + parseFloat("0.56") + parseFloat("0.10");
console.log(x);
console.log(x === 1);

Related