Wilf Wilf - 23 days ago 6
Javascript Question

Add (or multiply, subtract or divide) one var to another in JS/jQuery

Sincere apologies if this has been asked and answered elsewhere, I struggled with finding accurate search terms for this.

Working in jQuery I have a

var
called
total
. I need to add the value of other
vars
to
total
. All the
vars
in question have numerical values.

This is what I've tried:

var total = total+rocketspend;
$(".totalamount").html(total);


and

var newtotal = total+rocketspend;
var total = newtotal;
$(".totalamount").html(total);


Both have resulted in
.totalamount
being emptied and replaced with nothing. I have theories around why this might be going wrong - it could be that in the first example a
var
isn't allowed to be self defining, and it could be that in in the second example the browser attempts to define both
newtotal
and
total
at the same time, ending in mystery. Or it could be something else entirely. The
rocketspend
var
works fine on its own, as does
total
before the attempted addition.

Thoughts?

Answer

You only need to use var when you first define a variable. It looks like you're trying to access a variable that already exists. Example:

var total = 0;
var rocketspend = 10;

total = total + rocketspend;
$(".totalamount").html(total);

Additionally, try checking your console for any errors. In most browsers, you can right click and inspect an element or click Ctrl + Shift + I and clicking on the Console tab. You can use Ctrl + Shift + K in Firefox.

Comments