Sunday, January 09, 2011

Backspace event on input fields

As a part of my job, I had to write code which would do something when the user hits the backspace on an input field (type=text). At first glance, this looked like a piece of cake. I listened to keydown event of input field and invoked the logic when the event keycode is 8 (browser sets the keycode of the event to 8 on backspace).

function OnKeyDownEventHandler(e)
{
if(e===null) e=window.event;
if(e!= null && typeof e != 'undefined')
{
if(e.keyCode===8)
{
// That means user tapped on backspace
// Run your logic here
}
}
}

This logic ran smoothly on all the different versions of iOS (iPhone and iPod). But this logic would fail on iphone 3 and lower devices when the value of the input field is empty. In that case, for some reason, browser would fire event with keycode as 127 and that too multiple times ! So, I had to make sure that I would listen for event with keycode of 127 and also had to make sure that I invoke my logic only once by maintaining a boolean flag. Also note that some android devices, for example, Samsung Focus (Android 2.1 and I think on 2.2 also) would not fire any event when the value of the input field is empty and user hits backspace. There were some other android devices which had the similar.

In short, you would expect simple things like this would work on atleast webkit browsers on mobile devices but sadly it does not. Make sure you know which devices you are going to support for your application and test your logic on those devices ( running on different versions of OS too, my experience tells me that Android 2.2 is well behaved than Android 2.1) and test your application with extensive test cases.

No comments: