输入元素上的 Javascript 更改事件仅在失去焦点时触发

标签 javascript jquery dom-events

我有一个输入元素,我想继续检查内容的长度,每当长度变得等于特定大小时,我想启用提交按钮,但我遇到了 Javascript 的 onchange 事件问题因为事件仅在输入元素超出范围时触发,而不是在内容更改时触发。

<input type="text" id="name" onchange="checkLength(this.value)" />

----onchange 不会在更改 name 的内容时触发,而只会在 name 失去焦点时触发。

我可以做些什么来使此事件在内容更改方面发挥作用?或者我可以为此使用的其他一些事件? 我通过使用 onkeyup 函数找到了一个解决方法,但是当我们从浏览器的自动完成器中选择一些内容时,它不会触发。

我想要一些东西,当字段的内容通过键盘或鼠标发生变化时,它可以工作……有什么想法吗?

最佳答案

(function () {
    var oldVal;

    $('#name').on('change textInput input', function () {
        var val = this.value;
        if (val !== oldVal) {
            oldVal = val;
            checkLength(val);
        }
    });
}());

这将捕获change、击键、pastetextInputinput(如果可用)。并且不要开火超过必要。

http://jsfiddle.net/katspaugh/xqeDj/


引用资料:

textInput — W3C DOM Level 3 事件类型。 http://www.w3.org/TR/DOM-Level-3-Events/#events-textevents

A user agent must dispatch this event when one or more characters have been entered. These characters may originate from a variety of sources, e.g., characters resulting from a key being pressed or released on a keyboard device, from the processing of an input method editor, or resulting from a voice command. Where a “paste” operation generates a simple sequence of characters, i.e., a text passage without any structure or style information, this event type should be generated as well.

输入HTML5事件类型。

Fired at controls when the user changes the value

Firefox、Chrome、IE9和其他现代浏览器都支持它。

This event occurs immediately after modification, unlike the onchange event, which occurs when the element loses focus.

关于输入元素上的 Javascript 更改事件仅在失去焦点时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7105997/

相关文章:

javascript - 如何检测浏览器(不是窗口)关闭事件

javascript - 如何使用 Node.js 解压文件

javascript - 当原型(prototype)为 "enter"时从表单调用函数

javascript - 如何使用 AngularJS ngShow 指令仅显示数组中的元素?

javascript - 不在桌面版时隐藏 Logo

javascript - 如何在选项卡关闭时删除 jquery cookie

php - 使用 AJAX 加载表单将在提交失败后丢失表单和值

javascript - 如何在尴尬的情况下获取复选框的值

javascript - 什么 HTTP 状态代码在 XMLHttpRequest 上触发错误事件

javascript - 如何在文本框的开头和结尾 trim 空格?