在jQuery中检测输入变化? [英] Detecting input change in jQuery?

查看:94
本文介绍了在jQuery中检测输入变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入上使用jquery .change 时,只有当输入失去焦点时才会触发事件

p>

在我的情况下,只要输入值改变,我就需要调用服务(检查值是否有效)。

解决方案

更新了澄清和示例



示例: http://jsfiddle.net/pxfunc/5kpeJ/

方法1. 输入事件



在现代浏览器中,使用 input 事件。这个事件会在用户输入文本字段时触发,粘贴,撤消,基本上任何时候值从一个值改变到另一个值。



在jQuery中是这样的

  $('#someInput')。bind('input',function(){
$(this) .val()//获取输入字段的当前值。
});

从jQuery 1.7开始,将 bind 替换为 on

  $('#someInput')。on输入',函数(){
$(this).val()//获取输入字段的当前值
});

方法2. keyup 事件



对于旧版浏览器,使用键盘事件(一旦键盘上的按键被释放,这个事件可以给出一种误报,因为当w被释放时,输入值被改变并且键入事件触发,但是当移位键释放键盘键事件触发,但输入没有改变。)。如果用户右键单击并粘贴上下文菜单,则此方法不会触发:

  $('#someInput' ).keyup(function(){
$(this).val()//获取输入字段的当前值
});

方法3.计时器( setInterval setTimeout $ b

为了解决 keyup 您可以设置一个计时器来定期检查输入值以确定值的变化。您可以使用 setInterval setTimeout 来执行此计时器检查。请参阅此SO问题上的标记答案: jQuery文本框更改事件或使用<$ c $查看小提琴工作示例c>焦点和 blur 事件来启动和停止特定输入字段的计时器


When using jquery .change on an input the event will only be fired when the input loses focus

In my case, I need to make a call to the service (check if value is valid) as soon as the input value is changed. How could I accomplish this?

解决方案

UPDATED for clarification and example

examples: http://jsfiddle.net/pxfunc/5kpeJ/

Method 1. input event

In modern browsers use the input event. This event will fire when the user is typing into a text field, pasting, undoing, basically anytime the value changed from one value to another.

In jQuery do that like this

$('#someInput').bind('input', function() { 
    $(this).val() // get the current value of the input field.
});

starting with jQuery 1.7, replace bind with on:

$('#someInput').on('input', function() { 
    $(this).val() // get the current value of the input field.
});

Method 2. keyup event

For older browsers use the keyup event (this will fire once a key on the keyboard has been released, this event can give a sort of false positive because when "w" is released the input value is changed and the keyup event fires, but also when the "shift" key is released the keyup event fires but no change has been made to the input.). Also this method doesn't fire if the user right-clicks and pastes from the context menu:

$('#someInput').keyup(function() {
    $(this).val() // get the current value of the input field.
});

Method 3. Timer (setInterval or setTimeout)

To get around the limitations of keyup you can set a timer to periodically check the value of the input to determine a change in value. You can use setInterval or setTimeout to do this timer check. See the marked answer on this SO question: jQuery textbox change event or see the fiddle for a working example using focus and blur events to start and stop the timer for a specific input field

这篇关于在jQuery中检测输入变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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