I have an input element and I want to keep checking the length of the contents and whenever the length becomes equal to a particular size, I want to enable the submit button, but I am facing a problem with the onchange event of Javascript as the event fires only when the input element goes out of scope and not when the contents change.

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

----onchange不会在更改名称的内容时触发,但只在名称失go 焦点时触发.

Is there something I can do to make this event work on content change? or some other event I can use for this? I found a workaround by using the onkeyup function, but that does not fire when we select some content from the auto completer of the browser.

我想要的东西,可以工作时,该领域的内容发生变化,无论是通过键盘还是鼠标...有什么 idea 吗?

推荐答案

(function () {
    var oldVal;

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

This will catch change, keystrokes, paste, textInput, input (when available). And not fire more than necessary.

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


References:

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

当一个或多个字符具有 已输入.这些字符可能起源于各种不同的 来源,例如,由按键或按键产生的字符 在键盘设备上释放,从输入法的处理中释放 编辑器,或由语音命令产生.其中"粘贴"操作 生成简单的字符序列,即文本段落 在没有任何 struct 或样式信息的情况下,此事件类型应为 也生成了.

input — an HTML5 event type.

当用户更改值时触发控件

Firefox, Chrome, IE9 and other modern browsers support it.

此事件在修改后立即发生,与onchange事件不同,onchange事件在元素失go 焦点时发生.

Jquery相关问答推荐

在Click事件上将焦点设置为Kendo UI网格列筛选器文本框

为什么在 jQuery 插件中返回 this.each(function())?

$.post 和 $.ajax 之间的区别?

jQuery - 向下滚动时缩小的粘性标题

jQuery 与 javascript?

JQuery/Javascript:判断 var 是否存在

一次替换多个字符串

jQuery Keypress 箭头键

在网络浏览器中,onblur 和 onfocusout 有什么区别?

为什么要两次声明 jQuery?

确定 JavaScript 值是否为整数?

jQuery $.cookie 不是一个函数

验证外部脚本是否已加载

如何使用jquery获取点击链接的href?

如何清除/重置 jQuery UI Datepicker 日历上的选定日期?

如何在 JavaScript 中的对象数组中查找值?

jQuery: Select 不为空的数据属性?

在事件中使用 jQuery 获取被点击的元素?

在某个点停止固定位置滚动?

.animate() 的回调被调用两次 jquery