最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

keypress - How can I prevent users from using the backspace or delete keys in a textbox using JavaScript? - Stack Overflow

programmeradmin5浏览0评论

How can I prevent users from using the backspace or delete keys in a textbox using JavaScript?

I have a text box in my web form. I want to use JavaScript on keypress of the textbox to disable the delete and backspace keys.

Can anyone help?

How can I prevent users from using the backspace or delete keys in a textbox using JavaScript?

I have a text box in my web form. I want to use JavaScript on keypress of the textbox to disable the delete and backspace keys.

Can anyone help?

Share Improve this question edited Aug 7, 2009 at 12:57 Andrew Hare 352k75 gold badges647 silver badges642 bronze badges asked Aug 7, 2009 at 12:50 hrishihrishi 1,5618 gold badges28 silver badges43 bronze badges 3
  • 4 If you can explain the scenario then it would be helpful. – rahul Commented Aug 7, 2009 at 12:53
  • 4 Don't forget Ctrl-X, choosing Cut from the menu, or the insert key. There are lots of ways to remove text from an input. – Joel Coehoorn Commented Aug 7, 2009 at 12:59
  • 1 Or selecting a block of text (with mouse or Ctrl+a or Shift+cursor) and then staring to type. – Keith Commented Aug 7, 2009 at 13:19
Add a ment  | 

3 Answers 3

Reset to default 13

Why are you letting people edit the contents of the text box but restricting them from being able to use basic editing keys? This sounds like you are creating a major usability issue - what if the user makes a typo?

I'd remend either setting the readonly flag (if you don't want users to edit the value) or disabled flag (if you don't even want it submitted)

Here's a bit of code to block the certain key press events - or something along those lines (haven't tested the code).

function isValidKey(e)
{
    var charCode = e.keyCode || e.which;
    if (charCode == 8 || charCode == 46)
        return false;

    return true;
}

<input id="tb_box" onkeydown="return isValidKey(event)" type="text" />

using javascript create function takes the event keyboard typing then avoid backspace (key-code 8) and delete (key-code 46) keys

function preventBackspace(e) {
  var evt = e || window.event;
  if (evt) {
      var keyCode = evt.charCode || evt.keyCode;
      if (keyCode === 8 || keyCode === 46) {
          if (evt.preventDefault) {
              evt.preventDefault();
          } else {
              evt.returnValue = false;
          }
      }
  }
}
<input onKeyDown="preventBackspace()" placeholder="Try write Something and enter backspace...">

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论