Setting onclick property for input

I need to set onclick property to the newly created element (input tag). It should be function with arguments. I use this: addButton.onclick = addToBasket(aHref[i].innerHTML, aHref[i].href);

But the problem is that this function calls automatically when window is loaded, but I need simply to set property. By the way if I use function without arguments like this: addButton.onclick = addToBasket; it works (isn't called automatically).

Answers


Use instead:

addButton.onclick = function(){
    addToBasket(aHref[i].innerHTML, aHref[i].href);
}

onclick expects a function-definition. Another possibility is:

addButton.onclick = addToBasket;

But in this last one you will need to get the args from the function's inside, or with global variables.

It is because when you use () you are invoking the function-definition which will return some value or undefined.


You probably want this:

addButton.onclick = function(){ addToBasket(aHref[i].innerHTML, aHref[i].href)};

The difference is that the addToBasket call here is done on click, not before.


Need Your Help

How to play/pause a continuous activity on Android?

java android android-activity

I made an application where I can choose the interval of time, in seconds, of how often the web-service is called from the device.

decompress deflate64

c# deflate compression dotnetzip

I've got a compressed string of bytes coming out of a database which I need to decompress so as to retrieve the rtf file in there. This is the requirement.