5

I'm making a Web application that tests typing speeds.

It gives the user some text to type, and an input box to type into. If the user types a wrong key, I'm using preventDefault on the produced key event to prevent the wrong character from being entered into the input box (I instead show the user an error message).

The problem is, preventDefault doesn't prevent backspaces from being entered. Ideally, since wrong keys presses will never be entered into the text box, it doesn't make sense to allow backspacing. If the user habitually hits backspace on a perceived error, it causes the text in the input box become incorrect. This doesn't affect the results of the test, it's just not an ideal situation.

How can I prevent backspacing in HTML5 input elements of type "text"?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • Do you actually need to *prevent* backspacing? Another approach may be to detect when it occurs, and then to replace the input element's box with what "should" be there. – Brandin Mar 08 '16 at 14:29
  • @Brandin I don't *need* to, but I'd like to. And I tried that, but the key press handler fires *before* the text is placed in the box, so I can't simply replace the back-spaced key, since it's not deleted until after the handler has fired. – Carcigenicate Mar 08 '16 at 14:53

1 Answers1

5

You need to detect onkeydown instead of onkeypress and it should work (tested on Firefox/Safari). On some browsers onkeypress is limited to printable characters, whereas onkeydown is for all key down events.

<!doctype html>
<html lang="en">
    <head>
        <script type="text/javascript">
            function no_backspaces(event)
            {
                backspace = 8;
                if (event.keyCode == backspace) event.preventDefault();
            }
        </script>
    </head>
    <body>
        <input id="typeHere" onkeydown="no_backspaces(event);"/>
    </body>
</html>
Michael Mulqueen
  • 1,033
  • 10
  • 11
  • Thanks. It ended up being slightly more complicated though, since if you use `onkeydown`, you have to manually capitalize letters. I ended up attaching both handlers, using `onkeypress` for printable characters, and `onkeydown` for non-printable characters. Seems to work as expected so far. – Carcigenicate Mar 09 '16 at 15:44