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
526 views
in Technique[技术] by (71.8m points)

javascript - Detect programmatic changes on input type text

Is there a way to get informed when a script changes the value of an input type text.

I have

<input id='test' type='text' />

and a script

document.getElementById('test').value = 'bbb'; 

I want to be notified of the change of the text.

I know I could be notified by keydown,keyup, onblur etcetera (which works if I am trying to track user typing) but what about if the change is done programmatically ?

Many thanks

p.s. No JQuery please or if jquery does it can somebody explain how it achieves it.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you're dealing with a modern browser, you can try with something like this:

var input = document.getElementById('test');
input._value = input.value;
Object.defineProperty(input, "value", {
    get: function() {return this._value;},
    set: function(v) {
        // Do your stuff
        this._value = v;
    }
});

This solution is good if you actually don't expect any user input (i.e., hidden type input fields), because it's extremely destructive of the DOM basic functionality. Keep that in mind.


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

...