user2132073 user2132073 - 4 months ago 16
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()
{
$('.receptivo').parent().hide();
$('.indicacao').parent().hide();
$('.interna').parent().hide();
var a = $('#cp-forma-captacao').val();
console.log(a);

switch( $('#cp-forma-captacao').val() ) {
case 'contato_receptivo':
$('.receptivo').parent().show();
break;
case 'indicacao':
$('.indicacao').parent().show();
break;
default:
$('.interna').parent().show();
break;
}
}

formaCaptacao();

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


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

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


But it does not work. It's like the
change()
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...

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

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

var formCaptaco = function() { console.log('example!'); }
$('#selector').change(formCaptacao);

...it might make more sense (it's actually slightly more complicated than that in reality, see this answer for a description of the differences).