Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / Javascript

Prevent backspace in a dropdown from acting as the back button, with jQuery

Rate me:
Please Sign up or sign in to vote.
4.36/5 (8 votes)
16 Apr 2009CPOL3 min read 51K   17   4
Don't let hitting backspace in a dropdown cause a back navigation!

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:

ASP.NET
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Backspacing in a dropdown</title>
</head>
<body>
    <form>
    Backspacing here doesn't do anything:
    <input type="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:

HTML
<script type="text/javascript" 
   src="http://code.jquery.com/jquery-latest.js"></script>

Now, our page is plugged in to the awesome power of jQuery! We are going to focus on three of jQuery's features: document.ready, selectors, and event handlers.

We know we only want to change how the dropdowns handle the backspace, so we will use this selector:

JavaScript
$('select') ...

This tells jQuery that we are trying to do something to every <SELECT> tag on the page. What are we trying to do? Well, we need to handle some key events.

JavaScript
$('select').keypress(function(event) { ... });
$('select').keydown(function(event) { ... });

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.

JavaScript
if (event.keyCode == 8) {
  return false;
}

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:

JavaScript
function cancelBackspace(event) {
    if (event.keyCode == 8) {
        return false;
    }
}

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.

JavaScript
$('select').keypress(function(event) { return cancelBackspace(event) });
$('select').keydown(function(event) { return cancelBackspace(event) });

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.

JavaScript
$(document).ready(function() { 
    $('select').keypress(function(event) { return cancelBackspace(event) });
    $('select').keydown(function(event) { return cancelBackspace(event) });
}); // ready

Now, let's see the entire page!

HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Backspacing in a dropdown</title>
    <script type="text/javascript" 
       src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
    <form>
    Backspacing here doesn't do anything:
    <input type="text" /><br />
    Backspacing here acts as a Back button:
    <select>
    </select>
    </form>

    <script type="text/javascript">
        $(document).ready(function() { // FF needs keypress, IE needs keydown
            $('select').keypress(function(event) 
               { return cancelBackspace(event) });
            $('select').keydown(function(event) 
               { return cancelBackspace(event) });
        }); // ready

        function cancelBackspace(event) {
            if (event.keyCode == 8) {
                return false;
            }
        }
    </script>

</body>
</html>

The textbox is unaffected and behaves normally. But, you'll find that when you select a dropdown and hit backspace, nothing happens! No back button behavior...

Nice and safe, and we won't have any more users complaining about random form disappearance!

Points of interest

Remember that Internet Explorer needs a keydown event to handle a backspace, and Safari and Firefox need a keypress event. There is no harm in attaching both of them.

History

  • Version 1.0: Created!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 4 Pin
SkGyan3-Jan-11 0:45
SkGyan3-Jan-11 0:45 
GeneralMy vote of 3 Pin
PRASHANTPATIL498729-Aug-10 22:07
PRASHANTPATIL498729-Aug-10 22:07 
Generalanother solution Pin
Saeedses9-Jun-09 20:54
Saeedses9-Jun-09 20:54 
GeneralGreat article Pin
Michael Brookie18-Apr-09 12:57
Michael Brookie18-Apr-09 12:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.