Sunday, 30 June 2013

Keyup event not responding to preventDefault()

I was working on jQuery's autocomplete/ Bootstrap typeahead kind of thing for phpBB.
It is basically used to provide user with suggestion/options when user enters something in the input or textarea
Now the default behaviour that you will see of the following keys is as follows:

For Arrow Up
If some option was already selected, then select the option just above it.
If no option was selected previously then select the very last option.

For Arrow Down
If some option was already selected, then select the option just below the current option
If no option was selected then select the first option

For Enter button
Now when enter button is pressed, check if any option was selected by the user. If yes then, insert that options value in the input

Now here we have to supress default actions of these above buttons. As if users presses Upper button the cursor moves to the first position i.e. before the text so to suppress this action you will have to use
Event.preventDefault function. Now If you use this function inside keyup then this might not work as the event that you are trying to start has already happened. So instead of using keyup you will have to do use keydown as the event of the keydown happens before event of keyup. So the preventDefault was not working. Now you can suppress these actions using the preventDeafult

Happie Coding!! :)