仅允许文本(无特殊字符)并允许退格和删除

时间:2018-03-03 17:31:14

标签: javascript

Hellow all ..

是否有人可以帮助我在Js以下。现在它对我很好,但我不能使用退格。

在Js下面允许文本,我可以使用删除键,如何允许退格。

  $(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);
        });
    });

1 个答案:

答案 0 :(得分: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

&#13;
&#13;
$(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);
        });
});
&#13;
<!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>
&#13;
&#13;
&#13;

  

特殊键

     

资源管理器不会触发按键   删除,结束,输入,转义事件,   功能键,主页,插入,   pageUp / Down和tab。

     

如果您需要检测这些密钥,请帮忙并搜索其keyCode onkeydown / up ,并忽略onkeypress和charCode。

SOURCE

相关问题