Prevent backspace in input text box

末鹿安然 提交于 2021-02-10 11:13:09

问题


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"?


回答1:


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>


来源:https://stackoverflow.com/questions/35869026/prevent-backspace-in-input-text-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!