Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
});     
like image 669
user2014429 Avatar asked Feb 20 '13 22:02

user2014429


3 Answers

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.

like image 89
Plynx Avatar answered Oct 01 '22 23:10

Plynx


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

like image 36
Kevin B Avatar answered Oct 02 '22 00:10

Kevin B


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. :)

like image 27
Annie Shahid Avatar answered Oct 02 '22 00:10

Annie Shahid