简体   繁体   中英

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

如何输入输入框中的值?

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>

use an onchange event handler for the input box.

http://www.htmlcodetutorial.com/forms/_INPUT_onChange.html

I noticed you used the "jquery" tag. For jQuery, you can use the .keypress() method.

From the API documentation:

Description : Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.

The event will fire every time keyboard input is registered by the browser.

.keydown() and .keyup() are also available. Their behavior is slightly different from .keypress() and is outlined by the API documentation as well.

The nice thing about jQuery is that you can use the same code across Firefox, IE, Safari, Opera and Chrome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM