Calculate Sum in real time with JS

1

Cordial Greeting.

I hope you are well and can help me.

I have 2 inputs and when you are typing, you change to a currency format:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input name="N1" type="text"  id="Num1"  class="mis-adicionales">
    <input name="N2" type="text"  id="Num2"  class="mis-adicionales">
    <input name="Res" type="text" id="Res"  disabled="">

That thanks to the following 2 functions

  $("#Num1").on({
  "focus": function(event) {
    $(event.target).select();
  },
  "keyup": function(event) {
    $(event.target).val(function(index, value) {
      return value.replace(/\D/g, "")
        .replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ".");
    });
  }
});

$("#Num2").on({
  "focus": function(event) {
    $(event.target).select();
  },
  "keyup": function(event) {
    $(event.target).val(function(index, value) {
      return value.replace(/\D/g, "")
        .replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ".");
    });
  }
});

We are doing well so far.

What I want to do now, is that both are added automatically and the result is shown in the third input,

this is what I have:

<script type="text/javascript">

            $(document).ready(function() {

               $(document).on('click keyup','.mis-adicionales',function() {
                 calcular();
               });

            });

          function calcular() {
              var tot = $('#Res');
             // tot = tot.replace(/,/g, "");
              tot.val(0);
              $('.mis-adicionales').each(function() {
                  tot.val(parseFloat(tot.val()) + (isNaN(parseFloat($(this).val())) ? 0 : parseFloat($(this).val())));
              });
//          var totalParts = parseFloat(tot.val()).toFixed(3).split('0');
//          tot.val('$' + totalParts[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')); 

          var totalParts = parseInt(tot.val()).toFixed(3).split('.');
          tot.val('$' + totalParts[0].replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",") + '.' +  (totalParts.length > 1 ? totalParts[1] : ''));  
            }

</script>

I want to highlight that when there is more than 1 comma, "or more than 1 point". ", as it stops working and does not calculate well, the third input should also be in the form of a currency.

I hope you can help me

Thanks in advance.

    
asked by Andres Rodriguez 29.11.2018 в 22:09
source

1 answer

1

I will base my answer assuming that #Num1 and #Num2 are correct as you indicate.

If you notice, the input #Num1 and #Num2 you separate them by points ( . ) truth.

Now, in the function calcular you have a foreach which I assume you are extracting the values of #Num1 and #Num2 ( including points ).

At what moment within the foreach do you tell them to eliminate the points of each one of the input ?. You never do it and in each repetition the value returned by $(this).val() will always contain the points and when you apply the parseFloat it will not give an error but the result is not what was expected.

So I suggest that every time you do $(this).val() to the value returned you replace the points ( . ) in this way $(this).val().replace(/\./g, "")

At the end your foreach within the function calcular would be like this:

$('.mis-adicionales').each(function() {
    tot.val(parseFloat(tot.val()) + (isNaN(parseFloat($(this).val().replace(/\./g, ""))) ? 0 : parseFloat($(this).val().replace(/\./g, ""))));
});
    
answered by 01.12.2018 / 03:40
source