0

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));

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

4 Comments

@BrenGinthom Clearly, my code produces 10 as you can see with this snippet. If you are getting NaN in front of it, you aren't using my code as it's written.
@BrenGinthom You aren't following my code. You have this: $('#cost').text($(this).val()/100); which attempts to divide the value by 100, but does not convert the value to a number with parseInt() or parseFloat() first. HTML has one data type: string. If you get an HTML value and want to do math with it, you must convert it to a number first.
@BrenGinthom You also have a calculation set to run as soon as the user clicks into an element, but before they have a chance to enter any data into it. This will also cause NaN.
@BrenGinthom See my updated answer that is a bit closer to the code you shared (It's not very clear what your algorithm is). But, this shows how to extract the data, how to check it and how to do math with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.