Bren Ginthom
Bren Ginthom

Reputation: 119

Javascript: how to add number to DIV output?

I have a div with specified sum:

$('#cost')

I want add number 3 to this DIV output. My thing does not work:

+$('#cost').text(parseInt(3));

Upvotes: 0

Views: 262

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65806

Your code is overwriting the text with the number 3. You need to take the original value, parse the string it contains to get the numerical equivelant and then add 3 to that. The result of the math is then set back as the new value for the text of the element.

var $price = $('#price');
var $quantity = $('#quantity');
var $total = $('total');

$('#price, #quantity').on("input", function() {

  // Do conversions first:
  price = parseFloat($price.val());
  quantity = parseFloat($quantity.val());
  
  // Always check user input before using it
  // (What if the user types non-numeric data or leaves a field blank?)
  if(!isNaN(price) && !isNaN(quantity)){
    
    // Then the math is straignt-forward:
    $('#total').text(price * quantity);
    
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="price">
<input type="text" id="quantity">
<span id="total"></span>

Upvotes: 1

Related Questions