Saturday, April 4, 2015

jQuery text input change event

$('#test').on('input', function(e){
  console.log('test');
});

$('#test').on('keydown', function(e){
  console.log('test');
});

JavaScript events

This is when the different event are triggered:
  • change
    This will be called when the blur event is triggered if the value of the  has been changed. In other words it will trigger when the input loses focus the value is different to what it was.
  • input
    The input event is basically everything you are looking for, it captures the event on any input change and most likely came about due to the headaches causes when developing something that watches every keystroke. The input event even manages to catch the case where the mouse pastes in content.
    Unfortunately the input event is relatively new and only available to modern browsers (IE9+).
  • keydown
    The keydown event is pretty simple, it triggers when the user pushes the key down..
  • keypress
    The keypress event is supposed to represent a character being typed. Because of this is does not capture backspace or delete which immediately dismisses it for use over keydown.
  • keyup
    Much like keydown, it triggers whenever the user releases a key.
  • paste
    This handy event triggers when data is pasted into the element.

Modifier keys

Note that keydownkeypress and keyup carr with them information about the modifier keys ctrl shift and alt in the properties ctrlKeyshiftKey and altKey respectively.

The cases

Here is a list of the cases you need to consider:
  • Entering input with keyboard (includes holding down a key)
    Triggers: keydownkeypressinputkeyup
  • Deleting input (backspace/delete)
    Triggers: keydowninputkeyup
  • Pasting using ctrl+v
    Triggers: keydownpasteinputkeyup
  • Using mouse to paste
    Triggers: pasteinput
  • Select an item from the autocomplete (/)
    Triggers: keydownkeyup

Implementation

Given the above, you could implement your autocomplete box handling the input event for all changes to the input, and then keydown event to handling up and down. This would really separate everything nicely and lead to some pretty clean code.
If you want to support IE8, you will need to throw everything except pasting into the keydown event and then handle paste. The paste event is quite widely supported now and has been in IE since v5.5).

Reference:

http://stackoverflow.com/questions/15727324/for-a-javascript-autocomplete-search-box-must-we-use-the-input-event-handler

No comments: