Bruno
Bruno

Reputation: 1055

Automatically add values ​when filling input

I am adding the inputs when filling in and putting the result in another input:

$(".soma").blur(function(){

    var total = 0;

    $(".soma").each(function(){
        total = total + Number($(this).val());  
    });
    
    $("#sub").val(total);
});
  
  
$('.Preco').maskMoney({ decimal: '.', thousands: ' ', precision: 2 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>

<div class="form-group col-xs-1">                       
  <input type="text" class="form-control1 Preco soma" name="Valor[]" id="Valor" value="0.00" required>
  <span class="form-highlight">$</span>                     
  <span class="form-bar"></span>                        
  <label class="label1" for="Valor">Total</label>        
</div>

<div class="form-group col-xs-4">                       
  <input type="text" class="form-control1 Preco meuform" name="sub" id="sub" readOnly="true" value="">
  <span class="form-highlight">$</span>                     
  <span class="form-bar"></span>                        
  <label class="label1" for="sub">Total</label>        
</div>

The problem is that inserting more than 999.99 into the input no longer returns the sum, as shown in the example.

Upvotes: 0

Views: 46

Answers (1)

epascarello
epascarello

Reputation: 207557

When you add the space, the Number conversion fails since it is no longer a valid number. So you would need to remove the space when converting it.

$(".soma").blur(function(){

    var total = 0;

    $(".soma").each(function(){
        total = total + Number($(this).val().replace(/\s/g, ''));  
    });
    
    $("#sub").val(total);
});
  
  
$('.Preco').maskMoney({ decimal: '.', thousands: ' ', precision: 2 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>

<div class="form-group col-xs-1">                       
  <input type="text" class="form-control1 Preco soma" name="Valor[]" id="Valor" value="0.00" required>
  <span class="form-highlight">$</span>                     
  <span class="form-bar"></span>                        
  <label class="label1" for="Valor">Total</label>        
</div>

<div class="form-group col-xs-4">                       
  <input type="text" class="form-control1 Preco meuform" name="sub" id="sub" readOnly="true" value="">
  <span class="form-highlight">$</span>                     
  <span class="form-bar"></span>                        
  <label class="label1" for="sub">Total</label>        
</div>

Upvotes: 3

Related Questions