Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

javascript - Get value of variable inside .each() function jQuery

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");
    //} 
  });
});
question from:https://stackoverflow.com/questions/65915951/get-value-of-variable-inside-each-function-jquery

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...