Showing posts with label disable. Show all posts
Showing posts with label disable. Show all posts

Thursday, May 31, 2007

How to: Disable Backspace key in IE and Firefox

The problem

When a user presses the Backspace key on a page in Internet Explorer (IE) presses the back button, this is very frustrating when you have a form on the screen and accidently press backspace. And loose your page.

I watched one of my users enter data on a form, but was correcting some data in a text box and pressed backspace once too many times, and IE when BACK!!

Firefox is much better (at least it does not do a BACK on a text input), but it does do a back on other fields (e.g. a select)

The fix

Trap the onkeydown to ignore backspace. The code below also disables Enter unless on the Submit button

The Code
<script type="text/javascript">

// Trap Backspace(8) and Enter(13) - 
// Except bksp on text/textareas, enter on textarea/submit

if (typeof window.event != 'undefined') // IE
  document.onkeydown = function() // IE
    {
    var t=event.srcElement.type;
    var kc=event.keyCode;
    return ((kc != 8 && kc != 13) || ( t == 'text' &&  kc != 13 ) ||
             (t == 'textarea') || ( t == 'submit' &&  kc == 13))
    }
else
  document.onkeypress = function(e)  // FireFox/Others 
    {
    var t=e.target.type;
    var kc=e.keyCode;
    if ((kc != 8 && kc != 13) || ( t == 'text' &&  kc != 13 ) ||
        (t == 'textarea') || ( t == 'submit' &&  kc == 13))
        return true
    else {
        alert('Sorry Backspace/Enter is not allowed here'); // Demo code
        return false
    }
   }
</script>
FireFox Fix

You can disable the backspace action in firefox by going to "about:config" and changing "browser.backspace_action" to something other than "0" or "1", e.g. "2"

Google