12

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 ();
Ivan Ferić
  • 4,725
  • 11
  • 37
  • 47
pwp
  • 159
  • 1
  • 1
  • 9

3 Answers3

24

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.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
  • By the way, for @bert, this means your onclick handler is assigned "undefined" - because running this function which returns "undefined" assigns this result to onclick. – Mörre Feb 12 '13 at 09:38
  • @Lloyd So only parenthesis when declaring or calling, all the rest (which leafs only assigning?) without parenthesis? – pwp Feb 12 '13 at 10:07
  • Declaring or calling yes. For assignment just drop them. – Lloyd Feb 12 '13 at 18:40
3

If you want the function to be called on click then use

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

Update (As per query from WAO)

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

asifsid88
  • 4,631
  • 20
  • 30
1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335