I wonder why, as soon as the page loads, the function btw_bijtellen ()
is called. I wanted to call it by clicking...
var $ = function (id) {
return document.getElementById (id);
}
function btw_bijtellen () {
window.alert("we want to calculate something after clicking th button");
}
$("bereken").onclick = btw_bijtellen ();
You've added ()
which causes the function to execute.
For example:
var myFunc1 = function() {
alert('Hello');
}(); // <--- () causes self execution
var myFunc2 = function() {
return 5 + 5;
};
var some_value = myFunc2(); // <--- Again () causes execution (you'd expect this one)
In your case, as mentioned in comments you're basically telling the onclick
to set its value to the return value of the function.
If you drop the ()
it should run as expected.
If you want the function to be called on click then use
$("bereken").on('click', btw_bijtellen);
If you need to pass the argument, then you need to specify as the second argument. the $.on()
gets the data in the event
handler
$("bereken").on('click', {key1: value1, key2: value2, keyn: valuen}, btw_bijtellen);
where, you can get your parameters from event.data
var function = btw_bijtellen(event) {
var data = event.data;
console.log(data);
var key1 = event.data.key1;
console.log(key1); // this will output value1
}
Have a read on this link jQuery $.on() api
Putting ()
after a function name is how you call it.
If you want to assign the btw_bijtellen
to onclick
then remove the ()
from the last line of the code in the question.
With the ()
there, you are calling the function and assigning its return value to onclick
. Since that function has no return
statement, that value will be undefined
which is not what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With