Monday, January 10, 2011

The best way to handle keyup events for text input element

In general we will use "keyup" event in case if we need to display some results upon search keyword entered by the user. Anytime the user types the keyword, the callback function will be called and displays the result. For example: If user wants to search with "REST", the callback function will be called for 4 times, and the search keywords will be "R", "RE", "RES" and "REST" for each time.

This problem will not be solved even if you add some time out function to delay the call back event. If we add time out when calling the function, then callback function will be executed with the keyword "REST" for 4 times.
To solve this problem, there is a plugin called "TypeWatch" in jQuery which allows the user to enter full keyword, then it executes after some time delay:


Here is the function, which takes 5 parameters as the input.
// callback: The function to call
// wait: The number of milliseconds to wait after the the last key press before firing the callback
// highlight: Highlights the element when it receives focus
// captureLength: Minimum # of characters necessary to fire the callback

$("#search_groups").typeWatch( 
 wait : 750,
highlight:true, 
callback:renderSearchResult,
captureEnter : true,
minTextLength : 2
});
See demo here: http://dennydotnet.com/typewatch/index.htm
See the plugin: http://plugins.jquery.com/project/TypeWatch

Wednesday, January 5, 2011