-2

I would like to add a function call including parameters to a HTML button via javascript. I know there are plenty of questions to this subject but none of the answers i found did work for me.

Note: My HTML and JS are in separate files which are correctly linked (the JS code works)

Problem: I can add the function call like this:

var $add  = $("#add");
$add.click(myFunction);

However $add.click(myFunction(i)); does not work.(Did also try with specific integer)

I have also tried it the following way:

document.getElementById('add').onclick = function() {myFunction(i);};

But like that the function does not even get applied to the button.

My function is defined in the JS file like this:

function myFunction(length) {

//do stuff with length I would notice

}
Claudio Brasser
  • 511
  • 3
  • 20

1 Answers1

1

You can use some thing like function bind or do it using handler:

$add.click(function(e){
  myFunction(i);
});
  • works like a charm, thank you! Could you explain why this works and mine did not work ? – Claudio Brasser Aug 16 '17 at 09:22
  • 1
    you are used this : $add.click(myFunction(i)) So you are binding the return value of executed function **myFunction** not the function itself, binding is used for functions only. there is a deference between these two: var a = myFunction;var b = myFunction(i); //a: is a reference for function object, b: is the returned value from the called function. $add.click(handler) a function object to be abound with the click event. and it will called like : handler(e) //where e is the event object data triggered by the event – Haitham Adnan Mubarak Aug 16 '17 at 10:09