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
Assuming in your example that
.val()
is returning a number, consider what JavaScript would do with that number when you do this: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:
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.