简体   繁体   中英

event handler for input delete/undo

I need to check for all events which will change the contents of my text input. so far I have handlers for keyup, cut and paste. but the content can also be changed by highlighting the text and clicking delete or undo. is there a way to listen for these events?

$('#input').on('paste cut  keyup ',function() {
    //add delete and undo to listner
});     

You have more problems than this, you also have to worry about browsers with autofill features, etc. For this reason HTML5 has included the input event, which is included in modern browsers.

See this answer for a method of capturing every conceivable change event(*) the browser will let you capture, without firing more than once per change.

(*) Looks like they forgot cut , so add that in too.

I'd suggest using keydown and input : http://jsfiddle.net/vKRDR/

var timer;
$("#input").on("keydown input", function(){
    var self = this;
    clearTimeout(timer)
    // prevent event from happening twice
    timer = setTimeout(function(){
        console.log(self.value);
    },0);
});

keyup won't catch special keys such as ctrl, and input will catch things such as paste delete etc, even from context menu.

by using keydown and input, the event happens immediately rather than waiting for the user to release the button or blur the input.

keydown does most of the work, input picks up where keydown can't handle it such as the context menu delete/paste/cut

use these, they will get all the changes :

$(container).bind('keyup input propertychange paste change'), function (e){});

also, you could do one thing to check the value inside this onchange event:

$(function(){
  $('input').on('keyup input propertychange paste change', function(){
      if ($(this).data('val')!=this.value) {
          alert('Something has been changed in the input.');
      }
      $(this).data('val', this.value);
  });
});

hopefully, this will work in your case. :)

使用更改事件。

$('#input').on('change', function(){});

You're at least missing keypress and change. I don't know if "change" works with those actions, I do know that change is often just called when the input element loses focus.

Use this to detect deleting action on input value

document.getElementById("my_id_name").oninput = function(e) {
     if ((e.inputType == 'deleteContentBackward') || (e.inputType == 'deleteContentForward') || (e.inputType == 'deleteByCut')){
            $('my_id_name').value = null
        })
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM