tags:

views:

323

answers:

3

This works in IE, but I cannot get it to work in Opera or Firefox. I want to prevent Backspace from navigating away if and only if the current focus is the SELECT dropdown.

<html>
<body>
<select id="testselect">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>
<script language="javascript">
    document.getElementById("testselect").onkeydown = function(e) {
     if(!e) {
      e = event;
     }
     alert(e.keyCode);
     if (e.keyCode == 8 || e.keyCode == 46) {
       e.returnValue = false;

        e.cancelBubble = true;
        if (e.stopPropagation) { e.stopPropagation(); alert("stoppropagation");}
        if (e.preventDefault) { e.preventDefault(); alert("preventdefault");}
        return false;
     }
    };
</script>
</body>
</html>
A: 

You might want to check out the source code for the project from this article. He goes into detail about how he had to contend with the backspace key in different browsers.

Robert Harvey
A: 

That's trickier than I would have thought. Depending on the reason you are preventing the user from backspacing away from the page, something like this might work for you:

<script type="text/javascript">

        var bShowWarning = false;

        document.getElementById("testselect").onkeydown = function(e) {
            if (!e) {
                e = event;
            }
            if (e.keyCode == 8 || e.keyCode == 46) {
                bShowWarning = true;
            }
        };

        function UnLoadWindow() {
            if (!bShowWarning) return;
            return 'If you leave the page your data will be lost.';
        }

        window.onbeforeunload = UnLoadWindow;
    </script>
fordareh
A: 

Well, turns out that Opera needs the event to be cancelled in the onkeypress event, not onkeydown.

Reference: http://jimblackler.net/blog/?p=20

hova