Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery bind to keyup only, not focus

This seems like a simple thing but google hasn't turned up anything for me:

How can I bind to a text / value change event only, excluding an input gaining focus? Ie, given the following:

$(function(){
  $('input#target').on('keyup', function(){
    alert('Typed something in the input.');
  });
});

...the alert would be triggered when the user tabs in and out of an element, whether they actually input text or not. How can you allow a user to keyboard navigate through the form without triggering the event unless they input/change the text in the text field?

Note: I'm showing a simplified version of a script, the reason for not using the change event is that in my real code I have a delay timer so that the event happens after the user stops typing for a second, without them having to change focus to trigger the event.

like image 894
Andrew Avatar asked Apr 15 '12 02:04

Andrew


1 Answers

Store the value, and on any key event check if it's changed, like so:

$(function(){
  $('input#target').on('keyup', function(){
      if ($(this).data('val')!=this.value) {
          alert('Typed something in the input.');
      }
      $(this).data('val', this.value);
  });
});​

FIDDLE

like image 157
adeneo Avatar answered Oct 01 '22 19:10

adeneo