Search code examples
jqueryparameter-passingonchangeeventtrigger

How to pass html element reference via .change trigger


I have a function named showStuff() that I want called once during init and again when a select field changes. I need to pass a class or id name to the function but this won't work:

$('.filterChange').change($('#htmlElement'), showStuff);

What am I doing wrong? workaround is to call a generic function on change and from there call the showStuff() but I don't understand why the change trigger doesn't work. Same issue with .bind trigger.


Solution

  • You should pass that as an Map as that is the accepted syntax.

    $('.filterChange').change({'myelement': $('#htmlElement')}, showStuff);
    
    function showStuff(e) {
       $(e.data.myelement.show());
    }
    

    I think what you want is a simple inner function like below,

    $('.filterChange').change(function () {
       showStuff($('#htmlElement'));
    }).change(); //trigger during init or simply call showStuff($('#htmlElement'))