0
<script language="Javascript">
function monthlyPayment (form) {
    var down = form.dPayment.value;
    var trade = form.tradeIn.value;
    var totalDown = down + trade;

alert ("Total down is " + totalDown);
}
</script>

This is a beginner question as I'm new to Javascript... but I am just trying to make a mock up of a feature I'm trying to implement on my website.

I have a form with two user definable variables for 'Down Payment' and 'Trade-In'. Everything in the code works, except for when it "add's" the numbers (such as $100 + $200), it doesn't output $300, but instead $100200. When I change the sign to multiplication it outputs a correct value.

What am I missing? Is there some .sum or .math code I need to implement? Or is my entire script screwed?

Thank you all for your time and help.

mrmills129
  • 51
  • 1
  • 10
  • Use `parseInt` or `parseFloat` or `Number` or `+` on the value taken from DOM to convert it to Numer – Tushar Sep 22 '15 at 14:53
  • form values are STRINGS. if you want them to be treated as numbers, you'll have to convert them to numbers first. – Marc B Sep 22 '15 at 14:54

1 Answers1

0

This is a very common mistake people new with javascript make. the + sign is used to concatenate in javascript, which explains your result is 100200 when you try. What you give him is string, so he just concatenates the two.

use the Number() function to make sure their types become "Number" so your addition will work correctly.

var totalDown = Number(down) + Number(trade);
Enjoyted
  • 1,131
  • 6
  • 15