html catch event when user is typing into a text input

53,495

Solution 1

Use the keyup event to capture the value as the user types, and do whatever it is you do to search for that value :

$('input').on('keyup', function() {
     if (this.value.length > 1) {
          // do search for this.value here
     }
});

Another option would be the input event, that catches any input, from keys, pasting etc.

Solution 2

Why not use the HTML oninput event?

<input type="text" oninput="searchContacts()">

Solution 3

I would use the 'input' and 'propertychange' events. They fire on cut and paste via the mouse as well.

Also, consider debouncing your event handler so that fast typists are not penalized by many DOM refreshes.

Share:
53,495

Related videos on Youtube

Matt
Author by

Matt

By Day: R&amp;D Manager at a software company that develops Enterprise software for companies throughout the world. By Night: A devoted husband and father of 2. Enthusiast of lifting heavy weights at the gym and enjoying company of friends.

Updated on July 25, 2022

Comments

  • Matt
    Matt almost 2 years

    Im just wondering how I go about catching the event when the user is typing into a text input field on my web application.

    Scenario is, I have a contacts listing grid. At the top of the form the user can type the name of the contact they are trying to find. Once there is more than 1 character in the text input I want to start searching for contacts in the system which contain those characters entered by the user. As they keep typing the data changes.

    All it is really is a simple type ahead type functionality (or autocomplete) but I want to fire off data in a different control.

    I can get the text out of the input once the input has lost focus fine, but this doesnt fit the situation.

    Any ideas?

    Thanks

  • Curtis Yallop
    Curtis Yallop almost 9 years
    Note that if you cut/paste with the mouse, keyup won't fire but the input value will change. You can also add "cut paste" to the events if this is important.
  • Curtis Yallop
    Curtis Yallop almost 9 years
    Note that if you type a key then quickly hit tab to go to the next control, keyup does not always fire. If you catch "blur", that handles this case. Although adding this event here would make the search fire every time you click off the input.
  • adeneo
    adeneo almost 9 years
    @CurtisYallop - Note that the question says "...when the user is typing", if you want to catch all changes in the value, the input event will do that.
  • Pablo Ariel
    Pablo Ariel over 4 years
    It's not fun without unnecessary overhead.