Can jQuery check whether input content has changed

2019-01-31 11:14发布

Is it possible to bind javascript (jQuery is best) event to "change" form input value somehow?

I know about .change() method, but it does not trigger until you (the cursor) leave(s) the input field. I have also considered using .keyup() method but it reacts also on arrow keys and so on.

I need just trigger an action every time the text in the input changes, even if it's only one letter change.

9条回答
爷、活的狠高调
2楼-- · 2019-01-31 12:06

I had to use this kind of code for a scanner that pasted stuff into the field

$(document).ready(function() {
  var tId,oldVal;
  $("#fieldId").focus(function() {
     oldVal = $("#fieldId").val();
     tId=setInterval(function() { 
      var newVal = $("#fieldId").val(); 
      if (oldVal!=newVal) oldVal=newVal;
      someaction() },100);
  });
  $("#fieldId").blur(function(){ clearInterval(tId)});
});

Not tested...

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-31 12:08

There is a simple solution, which is the HTML5 input event. It's supported in current versions of all major browsers for <input type="text"> elements and there's a simple workaround for IE < 9. See the following answers for more details:

Example (except IE < 9: see links above for workaround):

$("#your_id").on("input", function() {
    alert("Change to " + this.value);
});
查看更多
家丑人穷心不美
4楼-- · 2019-01-31 12:10

I don't think there's a 'simple' solution. You'll probably need to use both the events onKeyUp and onChange so that you also catch when changes are made with the mouse. Every time your code is called you can store the value you've 'seen' on this.seenValue attached right to the field. This should make a little easier.

查看更多
登录 后发表回答