简体   繁体   中英

Preventing the user from deleting in an input field

提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供   中文简体   中文繁体   中英对照 版本,有任何建议请联系yoyou2525@163.com。

I want to have a text field ( <input> in HTML) that the user can only use to write text, but when deleting the text, it should prevent him from updating the state of the input element.

 <input type="text" />

I couldn't come up with a solution except to detect the user key presses on the keyboard, ie, using the onKeyUp attribute, and watch the user keystrokes until he presses the Backspace character:

 const input = document.querySelector('input') input.addEventListener('keydown', (e) => { const keyCode = e.keyCode if (keyCode === 8) console.log("Backspace pressed!") })
 <input type="text" />

However, there's a missing part here, even though the user won't be able to clear the input content by the Backspace key, he can instead use the Del key. So I would have then to handle the Del key the same way I handle the Backspace key.

Now, there's another problem, which is trying to modify the input content by overwriting the content as follows:

在此处输入图像描述

and then, after that, I will have to prevent the user from editing the text by cutting the content (which I have no idea how to do).

So, what are the alternatives?

Please feel free to use HTML, JavaScript, CSS, or even React.

No answers.You can refer to the related questions on the right.
暂无
暂无

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2022 STACKOOM.COM