javascript function running without being called

21,789

Solution 1

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.

Solution 2

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

Solution 3

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.

Share:
21,789
pwp
Author by

pwp

Updated on July 05, 2022

Comments

  • pwp
    pwp almost 2 years

    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 ();
    
  • Mörre
    Mörre over 11 years
    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.
  • pwp
    pwp over 11 years
    @Lloyd So only parenthesis when declaring or calling, all the rest (which leafs only assigning?) without parenthesis?
  • Lloyd
    Lloyd over 11 years
    Declaring or calling yes. For assignment just drop them.
  • Wylan Osorio
    Wylan Osorio almost 9 years
    what if you want to pass an argument to 'btw_bijtellen' function?