JS Events: hooking on value change event on text inputs

I can’t find a suitable event for that.

Yeah, there isn’t one.

There are DOM Mutation Events, but they aren’t supported well cross-browser, and don’t fire for form values anyway as those aren’t reflected in attributes (except in IE due to a bug).

In Mozilla only, a JavaScript watch could be set on the value property to catch scripted changes. In IE only, a JScript onpropertychange handler could be set to catch both scripted and user-driven changes. In other browsers you would have to use your own interval poller to look for changes.

function watchProperty(obj, name, handler) {
    if ('watch' in obj) {
        obj.watch(name, handler);
    } else if ('onpropertychange' in obj) {
        name= name.toLowerCase();
        obj.onpropertychange= function() {
            if (window.event.propertyName.toLowerCase()===name)
                handler.call(obj);
        };
    } else {
        var o= obj[name];
        setInterval(function() {
            var n= obj[name];
            if (o!==n) {
                o= n;
                handler.call(obj);
            }
        }, 200);
    }
}

watchProperty(document.getElementById('myinput'), 'value', function() {
    alert('changed!');
});

This is highly unsatisfactory. It won’t respond to user-driven changes in Mozilla, it allows only one watched property per object in IE, and in other browsers the handler function will get called much later in execution flow.

It’s almost certainly better to rewrite the parts of script that set value to call a setValue wrapper function instead, that you can monitor for changes you want to trap.

Leave a Comment