Javascript function works without calling

I wonder why, as soon as the page loads, the function is called btw_bijtellen (). I wanted to call him 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 ();
+5
source share
3 answers

You have added ()which calls the execution of the function.

For instance:

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 stated in the comments, you basically say onclickto set its value to the return value of the function.

If you let go (), it should work as expected.

+14
source

If you want the function to be called when clicked, use

$("bereken").on('click', btw_bijtellen);

Update (as requested by WAO)

, . $.on() event

$("bereken").on('click', {key1: value1, key2: value2, keyn: valuen}, btw_bijtellen);

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
}

jQuery $.on() api

+3

Place ()after the function name what you call it.

If you want to assign btw_bijtellento onclick, then remove ()from the last line of code in the question.

With the help of ()you call the function and assign its return value onclick. Since this function has no operator return, this value will be undefined, which is not what you want.

0
source

All Articles