modeller modeller - 5 months ago 15
jQuery Question

Event handler not triggered on specified event

I am implementing an user-input form with complex data-field dependencies. For example, a form that collects user's address: country, state, and street-address.

When the country field is changed, I want to trigger the cleaning process of state field. When state is changed, I want clean street-address field. They are chained like a dependency tree structure.

Here is my setup in JSFiddle. It contains 5 input boxes. Their dependency tree is implemented with HTML5 data attributes.

I want to bind a function

cleanSubtree
to each input box's
change
event. So whenever a change is detected, this function will clean all dependent fields. As below:

$('input').on('change',function cleanSubtreeHandlerWrapper(e){
var inputElem = $(this);
return function(){
e.stopPropagation();
cleanSubtree(inputElem);
};
});


However, when I change text of any input box, the bounded function seems not executing.
But the function will work correctly if I call them directly, e.g.
cleanSubtree($('#i3'));
.

May I know what could the the cause of
cleanSubtree
function not triggered?

(PS: I am using jQuery 2.1.4 and Chrome 51.0.2704.103 m)
EDIT: The fix is to change wrapper function. The previous version did not call the wrapper function.

$('input').on('change',
function cleanSubtreeHandlerWrapper(e){ //** seems not triggered
e.stopPropagation();
cleanSubtree($(this));
});

Answer

change :

     $('input').on('change',function processNodeHandlerWrapper(e){
        var inputElem = $(this);
    return function(){
        e.stopPropagation(); 
        cleanSubtree(inputElem);
    };
});

to :

<script>
    $('input').on('change',function processNodeHandlerWrapper(e){
        var inputElem = $(this);
        e.stopPropagation(); 
        cleanSubtree(inputElem);
      })
</script>
Comments