user2132073 user2132073 - 1 year ago 35
Javascript Question

Passing a function directly to a change() event does not work

I have to show or hide some divs according the value selected of a select. To do this, I have this block of code that works great:

$(document).ready(function($) {
function formaCaptacao()
var a = $('#cp-forma-captacao').val();

switch( $('#cp-forma-captacao').val() ) {
case 'contato_receptivo':
case 'indicacao':



On the bottom, when user changes the select value, I have to pass a function as parameter to the event
. I tried this:

$('#cp-forma-captacao').change( formaCaptacao() );

But it does not work. It's like the
event is never been called. Why? I'm just passing a function as parameter. Theoretically, it should work.

Answer Source

In your example, you're invoking the function instead of passing the reference to the function itself - so what you're actually passing into change() is the result of calling formaCaptacao (which will be undefined, since it never returns anything), not the function itself.

Try this instead...


If you think of it as though you're doing this...

var formCaptaco = function() { console.log('example!'); }
$('#selector').change(formCaptacao); might make more sense (it's actually slightly more complicated than that in reality, see this answer for a description of the differences).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download