我如何抓住从HTML表单输入框的值作为被输入? [英] How do I grab the value from an html form input box as its being entered?

查看:187
本文介绍了我如何抓住从HTML表单输入框的值作为被输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何抓住从一个输入框的值作为被输入?

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

推荐答案

的onkeyup释放按键时,每次将被触发。虽然它看起来是它存在一些问题。该溶液

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.

如果用户复制/粘贴用鼠标输入字段的值,或单击撤销/重做在浏览器中的onkeyup不会被触发。

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. 聚焦状态,存储领域的当前值,并启动间隔以检查修改
  2. 当用户输入移动的东西,有一个与旧值进行比较,如果不同的保存已经触发
  3. 的onblur ,当用户从现场移开,清除间隔时间和事件处理程序
  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>

这篇关于我如何抓住从HTML表单输入框的值作为被输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆