Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

javascript - JS Events: hooking on value change event on text inputs

I have a text input whose content is changed by a script not by user. So I would want to fire an event when the value changes. I can't find a suitable event for that. I even found this on StackOverflow, but it is not the solution I'm looking for.

How to make this work with jQuery and a text input where the value is set like this:

myTextControl.value = someValue

Here I want to fire an event to see the new value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...