Problem:

We all know if an input’s value was changed by user input, we can capture this change event by

$('input').change(function(event){
	console.log('user changed the value.');
});

But if the value was changed by a program, not by user, then the element won’t emit change event. In most cases, this won’t be a problem, because usually we only want to capture user’s behavior and make some responses. However, in some rare cases we still want to capture the programatic changing event. For example, in a multi-level cascading dropdown lists, we need to reload a dropdown’s options once the dependent dropdown’s value was changed, and the dependent dropdown might dependent on another dropdown or input whose value might be changed programatically.

How to capture or hook these changing event by javascript?

Solution:

The best way of doing this might be polling the element’s value intervally, and once a change was detected, emit a change event or just trigger the original user change event forcedly.

Code snippet:

    function checkChange($element) {
        var originalValue = $element.val();

        setInterval(function () {
                var currentValue = $element.val();
                if(currentValue !== originalValue) {
                    originalValue = currentValue;
                    $element.trigger('change');
                }
            }, 500);
    }");

Usage example:

    checkChange($('input'));

    $('input').change(function(event){
        console.log('The value was changed.');
    });