使用JQuery检测对<input type ="text">(立即)的所有更改

Dus*_*ell 385 html javascript jquery

a的价值<input type="text">可以通过多种方式改变,包括:

  • 按键
  • 复制粘贴
  • 用JavaScript修改
  • 通过浏览器或工具栏自动完成

我希望我的JavaScript函数在任何时候都会被调用(使用当前输入值).我希望它能立即被调用,而不仅仅是当输入失去焦点时.

我正在寻找在所有浏览器中执行此操作的最干净,最强大的方法(最好使用jQuery).

示例用例:在Twitter注册页面上,用户名字段的值显示在其下方的URL" http:// twitter/username "中.

pha*_*ann 344

这个jQuery代码捕获任何元素的即时更改,并且应该适用于所有浏览器:

 $('.myElements').each(function() {
   var elem = $(this);

   // Save current value of element
   elem.data('oldVal', elem.val());

   // Look for changes in the value
   elem.bind("propertychange change click keyup input paste", function(event){
      // If value has changed...
      if (elem.data('oldVal') != elem.val()) {
       // Updated stored value
       elem.data('oldVal', elem.val());

       // Do action
       ....
     }
   });
 });
Run Code Online (Sandbox Code Playgroud)

  • 我错了,或者当通过javascript改变文本时这不会处理,例如`document.getElementById('txtInput').value ='some text';` (66认同)
  • 对于每个人的参考,`input`是我认为应该涵盖所有现代浏览器的HTML5事件([MDN参考](https://developer.mozilla.org/en/DOM/window.oninput)).`keyup`应该捕获其余部分,但稍有延迟(按键时触发`input`).`propertychange`是一个专有的MS事件,我不确定`paste`是否真的是必要的. (19认同)
  • @MehmetAtaş是_partly_正确.`input`事件[here](http://help.dottoro.com/ljhxklln.php)的引用表明,当通过JavaScript修改内容时它不会触发.但是,`onpropertychange`事件_does_通过JS进行修改(见[here](http://help.dottoro.com/ljufknus.php)).因此,当在IE上通过JS修改内容时,此代码将起作用,但在其他浏览器上不起作用. (11认同)
  • Mehmet,代码并不意味着通过JS捕获更改的值. (4认同)
  • 您可以在propertychange,keyup等时触发输入上的自定义事件,然后在任何地方使用它. (2认同)

小智 120

jQuery> = 1.9的实时奇特解决方案

$("#input-id").on("change keyup paste", function(){
    dosomething();
})
Run Code Online (Sandbox Code Playgroud)

如果您还想检测"点击"事件,只需:

$("#input-id").on("change keyup paste click", function(){
    dosomething();
})
Run Code Online (Sandbox Code Playgroud)

如果你使用jQuery <= 1.4,只需使用live而不是on.

  • 这有一个缺点.如果您使用tab键保留输入字段 - 即使未编辑内容,它也会抛出keyup事件. (3认同)
  • 如何检测datetimepicker何时填充#input-id?没有任何事件(更改,粘贴)工作. (2认同)

Dus*_*ell 102

不幸的是,我认为setInterval获奖:

<input type=text id=input_id />
<script>
setInterval(function() { ObserveInputValue($('#input_id').val()); }, 100);
</script>
Run Code Online (Sandbox Code Playgroud)

这是最干净的解决方案,只有一行代码.它也是最强大的,因为您不必担心input可以获得价值的所有不同事件/方式.

在这种情况下,使用'setInterval'的缺点似乎不适用:

  • 100毫秒的延迟? 对于许多应用,100ms足够快.
  • 在浏览器上添加了负载? 通常,在页面上添加大量的重量级setIntervals是不好的.但在这种特殊情况下,添加的页面加载是不可检测的.
  • 它不能扩展到许多输入? 大多数页面没有多少输入,您可以在同一个setInterval中嗅探所有输入.

  • 这似乎是在使用Nintendo 3DS浏览器(版本/ 1.7552.EU)时检测表单中输入字段更改的唯一方法. (20认同)
  • @Gavin,在这个特殊情况下JS缺少事件..找到一组可以识别的事件,用户输入,用户粘贴,用户剪切,javascript插入,javascript删除,表单自动完成,隐藏表单,无显示形式. (11认同)
  • 你为什么要创建一个持续运行的100ms间隔,而没有理由让它一直运行?活动人士.使用它们. (10认同)
  • 注意:可以减轻过载.如果在输入获得焦点时启动setInterval,则在输入失去焦点时启动clearInterval (3认同)
  • @Gavin JS似乎没有触发每次更改输入时触发的onchanged事件.(只需执行document.getElementById(name).value = Math.random())以查看没有任何事件触发器解决方案有效. (2认同)
  • 也许这种方法可以帮助https://gist.github.com/inter-coder/d674758f727fa866f9e9,解决方案涵盖了元素不再存在的情况,然后消除了时间间隔 (2认同)

HRJ*_*HRJ 58

绑定到oninput事件似乎在大多数理智的浏览器中都能正常工作.IE9也支持它,但实现有bug(删除字符时不会触发事件).

使用jQuery 1.7+版本,该on方法可以像这样绑定到事件:

$(".inputElement").on("input", null, null, callbackFunction);
Run Code Online (Sandbox Code Playgroud)

  • ```oninput```事件不适用于```input [type = reset]```或javascript编辑,你可以在这个测试中看到:http://codepen.io/yukulele/pen/xtEpb (11认同)
  • @Yukulélé,至少我们可以比试图检测所有可能的**用户**动作更容易解决这个问题. (2认同)

Chr*_*oll 29

2017答案:输入事件对IE8的最新版本确实如此.

$(el).on('input', callback)
Run Code Online (Sandbox Code Playgroud)

  • 对不起,但是......这与2012年HRJ的回答有何不同?无论如何,`input`事件无法检测到JS的变化. (6认同)

Ann*_*lle 15

遗憾的是,没有符合您条件的事件或事件集.可以使用keyup事件处理键盘和复制/粘贴.通过JS进行的更改比较棘手.如果您可以控制设置文本框的代码,最好将其修改为直接调用函数或触发文本框上的用户事件:

// Compare the textbox's current and last value.  Report a change to the console.
function watchTextbox() {
  var txtInput = $('#txtInput');
  var lastValue = txtInput.data('lastValue');
  var currentValue = txtInput.val();
  if (lastValue != currentValue) {
    console.log('Value changed from ' + lastValue + ' to ' + currentValue);
    txtInput.data('lastValue', currentValue);
  }
}

// Record the initial value of the textbox.
$('#txtInput').data('lastValue', $('#txtInput').val());

// Bind to the keypress and user-defined set event.
$('#txtInput').bind('keypress set', null, watchTextbox);

// Example of JS code triggering the user event
$('#btnSetText').click(function (ev) {
  $('#txtInput').val('abc def').trigger('set');
});
Run Code Online (Sandbox Code Playgroud)

如果您无法控制该代码,则可以使用setInterval()"监视"文本框进行更改:

// Check the textbox every 100 milliseconds.  This seems to be pretty responsive.
setInterval(watchTextbox, 100);
Run Code Online (Sandbox Code Playgroud)

这种主动监控不会立即捕获更新,但似乎足够快,没有明显的滞后.正如DrLouie在评论中指出的那样,如果你需要观察大量的输入,这个解决方案可能无法很好地扩展.您可以随时调整第二个参数以setInterval()进行更频繁或更低频率的检查.


Tay*_*orS 13

这是一个不使用 jQuery 的解决方案(它确实已经过时并且现在没有必要)

使用该事件,"input"您可以查找任何类型的更改:

删除、退格、粘贴、键入以及任何会更改输入值的操作。

input事件与文本输入直接相关。任何时候文本以任何方式更改,input都会被发送。

document.querySelector("#testInput").addEventListener("input", test);

function test(e) {
    var a = document.getElementById('output');
    a.innerText += "Detected an Update!\n";
}
Run Code Online (Sandbox Code Playgroud)
<input id="testInput">
<br>
<a id="output"></a>
Run Code Online (Sandbox Code Playgroud)


Ped*_*der 6

如果你不喜欢任何其他答案,这里有一个稍微不同的解决方案:

var field_selectors = ["#a", "#b"];
setInterval(function() { 
  $.each(field_selectors, function() { 
    var input = $(this);
    var old = input.attr("data-old-value");
    var current = input.val();
    if (old !== current) { 
      if (typeof old != 'undefined') { 
        ... your code ...
      }
      input.attr("data-old-value", current);
    }   
  }   
}, 500);
Run Code Online (Sandbox Code Playgroud)

考虑到您不能依靠点击和键盘来捕获上下文菜单粘贴.