Introduction

I recently got a couple of defect tickets about users whose edit forms would randomly "go blank" when they were entering data. As it happens, when a user would hit backspace while a dropdown had the focus, the browser interoperated it as a Back button action.

This is a simple way to prevent users from accidentally browsing backwards when hitting the backspace key in a SELECT element.

Using the code

This very simple form in HTML has a textbox and a dropdown:

<htmlxmlns="http://www.w3.org/1999/xhtml"><head><title>Backspacing in a dropdown</title></head><body><form>
Backspacing here doesn't do anything:
<inputtype="text"/><br/>
Backspacing here acts as a Back button:
<select></select></form></body></html>

Browse to a site (such as http://www.codeproject.com), then browse to your sample form. Click on the textbox. You can sit on the backspace key as long as you like, and nothing will happen. But, when you focus on the dropdown and hit backspace, you'll find yourself looking at the previous page.

With some help from jQuery, we can solve this with a few simple lines of JavaScript!

First, we need to make sure the page references the jQuery library. Either download the jQuery library from the jQuery site at http://docs.jquery.com/Downloading_jQuery, or reference it directly from their site (which is what we will do).

We'll reference the library in our HTML page by adding this to our <head> section:

We're adding an event handler on all of our <SELECT> tags for both the keypress and keydown events. To handle those pesky backspaces, all we need to do is cancel the event if the keyCode value in the event indicates it's a backspace, which has a value of 8.

if (event.keyCode == 8) {
returnfalse;
}

I like to wrap that in a function so we can use it anywhere without having to repeat our code. Let's create a function that looks like this:

Now, we know that our function takes an event argument, checks the keyCode value for a backspace, and returns false if it matches. Let's put the pieces together by calling the function from the .keypress() and .keydown() functions.

The only thing left is to run this code when the document is fully loaded. jQuery handles that for us beautifully with $(document).ready(). We can include multiple ready() blocks and they will execute once the DOM is loaded.