html catch event when user is typing into a text input
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.
Related videos on Youtube
Matt
By Day: R&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, 2022Comments
-
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
-
nnnnnn over 11 yearsUse the keyup event.
-
-
Curtis Yallop almost 9 yearsNote 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 almost 9 yearsNote 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 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 over 4 yearsIt's not fun without unnecessary overhead.