Kirk
Kirk

Reputation: 441

Javascript: How can I block the backspace character?

I don't want my website's user to use backspace to go to the previous page,
but I still want to keep the use of backspace,
just like deleting wrong typing.
How can I do?

Thanks a lot.

Upvotes: 10

Views: 11392

Answers (7)

Another Day In Tech
Another Day In Tech

Reputation: 301

I finally found one that works on all browsers.

It's by Hazem Saleh His website address is: http://www.technicaladvices.com/2012/07/16/preventing-backspace-from-navigating-back-in-all-the-browsers/

/*Starts here:*/

  document.onkeydown = function (event) {

    if (!event) { /* This will happen in IE */
        event = window.event;
    }

    var keyCode = event.keyCode;

    if (keyCode == 8 &&
        ((event.target || event.srcElement).tagName != "TEXTAREA") && 
        ((event.target || event.srcElement).tagName != "INPUT")) { 

        if (navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
            event.stopPropagation();
        } else {
            alert("prevented");
            event.returnValue = false;
        }

        return false;
    }
  };  
/*Ends Here*/

Upvotes: 1

austincheney
austincheney

Reputation: 1199

Filme Noi Cinema has the right answer, but the example code is a bit dated. I just needed this solution so I thought I would post the code I used.

//I use the standard DOM method for accessing the body tag, because the
//non-standard HTML DOM shortcuts are not stable.  The correct behavior is
//dynamically attached to the entire body using the onkeypress event, which
//is the most stable event to target cross browser.
document.getElementsByTagName("body")[0].onkeypress = function (event) {
    var a = event || window.event, //get event cross browser
        b = a.target || a.srcElement; //get source cross browser

    //the only thing that matters is the backspace key
    if (a.keyCode === 8) {

        //if you are a textarea or input type text or password then fail
        if (b.nodeName === "textarea" || (b.nodeName === "input" && (b.getAttribute("type") === "text" || b.getAttribute("type") === "password"))) {
            return true;
        } else {

            //backspace is disabled for everything else
            return false;
        }
    }
};

This code needs to be executed before the user starts engaging the page. There are numerous ways to do this:

  1. You can put the above code into any function that is already attached to the onload event.
  2. You can wrap the above code that is bound to the page's onload event.
  3. You can put the above code into a self executing function.

Examples:

//self executing function
(function () {
    the solution code here
}());

//wrapper to onload event
document.getElementsByTagName("body")[0].onload = function () {
    the solution code here
};

I am adding this code to Pretty Diff if you want to see an example in action.

Upvotes: 1

Filme Noi Cinema
Filme Noi Cinema

Reputation: 111

Solution: Place the following code toward the end of all your pages that contain forms:

<!-- Block the Backspace and Enter keys in forms, outside of input texts and textareas -->
<script type="text/javascript">
    function blockBackspaceAndEnter(e) {
        if (!e) { // IE reports window.event instead of the argument
            e = window.event;
        }
        var keycode;
        if (document.all) {
            // IE
            keycode = e.keyCode;
        } else {
            // Not IE
            keycode = e.which;
        }
        // Enter is only allowed in textareas, and Backspace is only allowed in textarea and input text and password
        if ((keycode == 8
                && e.srcElement.type != "text"
                && e.srcElement.type != "textarea"
                && e.srcElement.type != "password")
                || (keycode == 13 && e.srcElement.type != "textarea")) {
            e.keyCode = 0;
            if (document.all) {
                // IE
                event.returnValue = false;
            } else {
                // Non IE
                Event.stop(e);
            }
        }
    }
    for (var i = 0; i < document.forms.length; i++) {
        document.forms[i].onkeydown = blockBackspaceAndEnter;
    }
</script>

I have the following comments about what other people answered here before:

Someone said:

"Please don't. Users like backspace-to-go-back; going back is one of the most vital browser features and breaking it is intolerably rude."

My answer to him is:

Yes, usually people DO use the back-button to go back, BUT NOT on pages with FORMS. On the other hand it is really easy for people to accidentally click near or outside an input text or textarea, and then press the back button, so they will lose all their edits, as someone else also noticed:

"Users aren't in a textbox and hit the backspace, completely losing all the form information they've just entered. Wouldn't normally be a problem, but for us, we're filling out lots of text on long state forms."

The same undesired behaviour can also be said about the Enter key to submit the form, which usually is only desirable (if ever) for small forms with a few fields, but not for forms with many fields and select boxes and input boxes and textareas, in which most of the time you DO NOT want that the form is submitted when you press Enter.

So this is why I suggest the code above, which applies to all <FORM> tags the function suggested by webster, but without the checks for ALT, which I don't think is useful, and without the checks for CTRL+N and CTRL+R and CTRL+F5, which we don't want to block, because when they are used they are NOT accidental.

Unfortunately, the code above does not work in Firefox when you have DIVs and TABLEs inside your FORM! That is because the keydown event seems to not be propagated to the containing form, and instead the default (UNDESIRED!) behaviour is applied for the Backspace and Enter keys. I couldn't yet find a solution for this one...

Upvotes: 11

Webster
Webster

Reputation: 11

You can simply use the following code snippets to block the backspace when the cursor is in texarea, text and password controls.

function onKeyDown() 
{    
    if((event.altKey) || ((event.keyCode == 8) &&
        (event.srcElement.type != "text" &&
        event.srcElement.type != "textarea" &&
        event.srcElement.type != "password")) ||
        ((event.ctrlKey) && ((event.keyCode == 78) || (event.keyCode == 82)) ) || (event.keyCode == 116) ) {
    event.keyCode = 0;
    event.returnValue = false;}
 } 

Call this function from body tag onkeydown event

Upvotes: 1

jthompson
jthompson

Reputation: 7266

As others have mentioned there are methods in which you can monitor for backspace key events and perform different actions.

I recommend against catching the backspace key for a couple of reasons:

1) It's simply irritating and irritated users are likely to not return to your page.

2) Backspace is not the only method of returning to the previous page. There are other key combinations that can accomplish the same thing, as well as the obvious "back button".

Don't do it - but if you must, use onbeforeunload() rather than trapping browser specific key strokes.

Upvotes: 11

fasih.rana
fasih.rana

Reputation: 1655

You can use the "onbeforeunload" property on the body tag to prompt the user that he is leaving the page.

Upvotes: 6

levik
levik

Reputation: 117529

You should be able to attach a onKeydown/Up/Press listener to your window. In this function, look at the keycode that was pressed, and at the event target. If the keycode is backspace, and the target is NOT an input box or a textarea, prevent the event.

Upvotes: 0

Related Questions