Always active calculation in JQuery

0

I need the following:

I have 3 input fields for values / currency. These values are not filled in sequence, other fields, with other values being populated between these 3 fields. I need to know, how do I make the result appear from the calculation of these 3 fields, only when the 3 values are filled, ie leave the formula always "active", "on", so that at any time the result is displayed, such as an Excel cell. I hope the question is clear.

    
asked by anonymous 28.05.2015 / 23:00

2 answers

1

You can use .change to check when these fields are affected and only display the result in a div or a span when the 3s have some value.

Example:

$(function() {
  $("#one, #two, #three").change(function() {
    if ($("#one").val() != "" && $("#two").val() != "" && $("#three").val() != "") {
        total = parseInt($("#one").val()) + parseInt($("#two").val()) + parseInt($("#three").val());
      $("#resultado").text(total);
    }
  });
});
#resultado {
  border: 1px solid;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><inputid="one" placeholder="Campo 1" type="number">
<br>
<input id="two" placeholder="Campo 2" type="number">
<br>
<input id="three" placeholder="Campo 3" type="number">
<br>
<div id="resultado"></div>
    
28.05.2015 / 23:26
0

So:

HTML:

<input type="text" class="data_value">
<input type="text" class="data_value">
<input type="text" class="data_value">

<span id="result"></span>

jQuery:

$('.data_value').keyup(function() {
    calc()
});

function calc() {
   var sum = 0;
   $('.data_value').each(function() {
      if ($(this).val() != '') {
        $("#result").text(sum += +$(this).val())
      }
   });
}

EXAMPLE JSFIDDLE

    
28.05.2015 / 23:35