【问题标题】:Allow Only Text (No special char) and allow backspace and delete仅允许文本(无特殊字符)并允许退格和删除
【发布时间】:2018-03-03 17:31:13
【问题描述】:

大家好..

有没有人可以在Js下面帮助我。现在它对我来说工作正常,但我不能使用退格键。

下面的Js允许文本,我可以使用delete键,如何允许退格。

  $(document).ready(function(){
        $("#inputTextBox").keypress(function(event){
            var inputValue = event.which;
            // allow letters and whitespaces only.
            if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0 )) { 
                event.preventDefault(); 
            }
            console.log(inputValue);
        });
    });

【问题讨论】:

  • 退格键码是 8

标签: javascript


【解决方案1】:

在 if 中使用退格键检查键码 8 并执行

if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0 ) && !(inputValue ==8)) { 
                event.preventDefault(); 
            }

供参考https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

$(document).ready(function(){
    $("input").keydown(function(event){
            var inputValue = event.which;
            // allow letters and whitespaces only.
            if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0) && (inputValue !=8) )
            { 
                event.preventDefault(); 
            }
            console.log(inputValue);
        });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>
<body>

  First name: <input type="text" name="FirstName" ><br>

</body>
</html>

特殊键

Explorer 不会触发按键 删除、结束、进入、转义的事件, 功能键,主页,插入, pageUp/Down 和 tab。

如果您需要检测这些键,请帮自己一个忙,搜索它们的 keyCode onkeydown/up,同时忽略 onkeypress 和 charCode。

SOURCE

【讨论】:

  • 不起作用。它接缝它允许一切正常
  • @MahmoodAbdullah 立即查看
  • 非常感谢..工作,我会做修改
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多