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

javascript - How do I grab the value from an html form input box as its being entered?

How do I grab the value from an input box as its being entered?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

onkeyup will be triggered every time a key is released. While it looks to be the solution it has some problems.

If the user move the cursor with the arrows, it is triggered and you have to check yourself if the field value didn't change.

If the user copy/paste a value in the input field with the mouse, or click undo/redo in the browser, onkeyup is not triggered.

Like in a mac or in google docs, I didn't want a save button to submit forms in our app, here is how I do it. Any comment, or shortcut is welcome as it is a bit heavy.

  1. onfocus, store the current value of the field, and start an interval to check for changes
  2. when the user moves something in the input, there is a comparison with the old value, if different a save is triggered
  3. onblur, when the user moves away from the field, clear the interval and event handlers

Here is the function I use, elm is the input field reference and after is a callback function called when the value is changed:

<html>
<head>
    <title>so</title>
</head>
<body>
    <input type="text" onfocus="changeField(this, fldChanged);">
    <script>
        function changeField(elm, after){
            var old, to, val,
                chk = function(){
                    val = elm.value;
                    if(!old && val === elm.defaultValue){
                        old = val;
                    }else if(old !== val){
                        old = val;
                        after(elm);
                    }
                };
            chk();
            to = setInterval(chk, 400);
            elm.onblur = function(){
                to && clearInterval(to);
                elm.onblur = null;
            };
        };
        function fldChanged(elm){
            console.log('changed to:' + elm.value);
        }
    </script>
</body>
</html>

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

...