Trigger code to +1 onClick?

I must apoligse to be posting such a simple question but I seem to have forgotten a lot of Javascript and have decided to get back into it by writing some client side programs as is the trend these days:)

All I need to do trigger some code when a button is clicked. I need it to add 1 to the variable “numberofbeers” each time - Then output the total again to the variable “beers”. It doesn’t work an I have no Idea why. I would be verry great full if you could help its driving me crazey:confused:

Here is my code…


var moneyinbank = 100;
var numberofbeers = 1;

function startgame(){

var beers = document.getElementById('beers');
beers.value = numberofbeers;

var bank = document.getElementById('bank');
bank.value = moneyinbank;
    
    function addonebeer() {
    nobeers=nobeers+1;
    }

var addbeer = document.getElementById('addbeer');
addbeer.onClick=(addonebeer());
}

Thank you for any response,

This sounds like a homework problem, but here’s the problem that you’re having, and the solution.

Currently you are assigning to the event the end result of executing the function. What you need to do instead is to assign only the name of the function to the event, so that whenever the event occurs, the event can then execute the function from within the context of the element that called the event in the first place.

Thanks Paul, I have tried to understand you answer…

assign only the name of the function to the event

I fort that was what I was doing?:confused:

addbeer.onClick=(addonebeer());

The () part invokes the function, so you are actually assigning to the event the returned value from running that function at that time, which will be undefined.

Do you know that functions exist as first-class objects that you can pass around just like variable names?