Detect all changes to a <input type=“text”>

2018-12-31 16:21发布

There are many ways the value of a <input type="text"> can change, including:

  • keypresses
  • copy/paste
  • modified with JavaScript
  • auto-completed by browser or a toolbar

I want my JavaScript function to be called (with the current input value) any time it changes. And I want it to be called right away, not just when the input loses focus.

I'm looking for the cleanest and most robust way to do this across all browsers (using jQuery preferably).

Example use case: On the Twitter Signup page, the username field's value gets shown in the url "http://twitter/username" below it.

16条回答
心情的温度
2楼-- · 2018-12-31 16:57

Here's a working example that I'm using to implement an autocomplete variation the populates a jqueryui selector (list), but I don't want it to function exactly like the jqueryui autocomplete which does a drop-down menu.

$("#tagFilter").on("change keyup paste", function() {
     var filterText = $("#tagFilter").val();
    $("#tags").empty();
    $.getJSON("http://localhost/cgi-bin/tags.php?term=" + filterText,
        function(data) {
            var i;
            for (i = 0; i < data.length; i++) {
                var tag = data[i].value;
                $("#tags").append("<li class=\"tag\">" + tag + "</li>");
            }
        }); 
});
查看更多
何处买醉
3楼-- · 2018-12-31 16:58

Binding to the oninput event seems to work fine in most sane browsers. IE9 supports it too, but the implementation is buggy (the event is not fired when deleting characters).

With jQuery version 1.7+ the on method is useful to bind to the event like this:

$(".inputElement").on("input", null, null, callbackFunction);
查看更多
何处买醉
4楼-- · 2018-12-31 16:59

Here is a slightly different solution if you didn't fancy any of the other answers:

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);

Consider that you cannot rely on click and keyup to capture context menu paste.

查看更多
泛滥B
5楼-- · 2018-12-31 17:00

Add this code somewhere, this will do the trick.

var originalVal = $.fn.val;
$.fn.val = function(){
    var result =originalVal.apply(this,arguments);
    if(arguments.length>0)
        $(this).change(); // OR with custom event $(this).trigger('value-changed');
    return result;
};

Found this solution at val() doesn't trigger change() in jQuery

查看更多
登录 后发表回答