Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript function running without being called

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 ();
like image 358
pwp Avatar asked Feb 12 '13 09:02

pwp


3 Answers

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.

like image 63
Lloyd Avatar answered Nov 04 '22 04:11

Lloyd


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

like image 20
asifsid88 Avatar answered Nov 04 '22 03:11

asifsid88


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.

like image 34
Quentin Avatar answered Nov 04 '22 03:11

Quentin