0

So I have this bit of code that goes like this

var number = 0;

function addnumber(numbertype){
 numbertype = numbertype +50;
}

function numberupdate() {
 document.getElementById('adiv').innerHTML = number;
}

Somewhere, I call

onClick="addnumber(number);"

Now, if I check the value of number with an alert, it displays correctly. But the number only goes to 50 once and doesn't climb the more I click, and even though an alert called within the addnumber() function will caluclate number correctly, it will not update the value of number when checked outside of that function.

I'm sure I'm missing something simple.

3 Answers3

0

In your addnumber function, the variable that you're passing in is getting increased by 50, not (I'm assuming) number.

You could change it to:

function addnumber(){
    number += 50;
}
Alex J
  • 1,029
  • 6
  • 8
0

You are confused with number and numbertype variable.

var number = 0;
function addnumber(numbertype){
    number = number + numbertype +50;
}

function numberupdate() {
    document.getElementById('adiv').innerHTML = number;
}
Iram
  • 278
  • 2
  • 6
  • Nah I want to use this function to be called to update a ton of completely different variables, like addnumber(number1); addnumber(number2); etc – Francis Berg Dec 24 '14 at 21:21
  • then use an array. function addnumber(index,numbertype){ number[index] = number[index] + numbertype +50; } – Iram Dec 24 '14 at 21:29
  • I got it now, just had to add window[] and some quotes in the onclick, thanks. I tried to answer this but the website somehow doesn't let me. – Francis Berg Dec 24 '14 at 21:32
0

Arguments to a javascript function are either passed 'by value' in case of primitives, or 'by reference' in case of objects. Your var 'number' is a primitive. In this case, a copy is made of the primitive value, and passed as the argument. Addnumber therefore adds 50 to a copy of number, not to number itself. When you want to change the value of a variable in this way, use an object, then it will work as you initially expected:

var number={value:0};

function addnumber(numbertype){
 numbertype.value = numbertype.value +50;
}
G. Moore
  • 77
  • 1