skip to Main Content

With jQuery, I’m doing some math to calculate a price. The math works, but I want to put a dollar sign in front of it, and when I try adding "$" + into the code, the math stops working correctly. How can I get the value of #totalprice to include the dollar sign?

$('#totalprice').val("$" + $('#qty1').val() * $('#price1').val() + $('#qty2').val() * $('#price2').val());

2

Answers


  1. Assuming in your example that .val() is returning a number, consider what JavaScript would do with that number when you do this:

    "$" + $('#qty1').val()
    

    The value "$" isn’t a number. (After all, what would $ + 5 equal?) It’s a string. So JavaScript coerces the number value into a string and concatenates.

    Basically the + operator means something different with strings than it does with numbers.

    Perform your logic in two distinct steps. First use the numbers to calculate a result, then concatenate that result into an output string. You can do this on the same line of code by grouping your mathematical expression with parentheses. For example:

    "$" + ($('#qty1').val() * $('#price1').val() + $('#qty2').val() * $('#price2').val())
    
    Login or Signup to reply.
  2. You are probably concatenating strings and not numbers because you start your argument with "$".
    Put some parenthesis around your math calculations (after "$" +).
    Also don’t forget to parse all those *.val() calls if you need to.
    And close your global .val() call; you forgot the last parenthesis.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search