Saturday, 3 March 2012

jquery .val() after key pressed

When entering data into a text input (for purposes such as auto-suggest), the following example code seems to always be one step behind, in other words .val() is called too early, i.e. seemingly before the keystroke is done:

$("#some-form-text-input").live("keypress", function(e){

An example of why this is undesirable is: if the text field already contained the string "somethin" and "g" is typed next, the alert in the callback would only display "somethin" versus the desired "something".

Solution: use the "keyup" rather than the "keypress" event


$("#some-form-text-input").live("keyup", function(e){

This waits until the latest pressed key is lifted before firing the callback.

No comments:

Post a Comment