JS函数允许只输入字母和空格

use*_*519 5 javascript jquery

我需要一个jquery或js函数来只允许输入字母和空格.提前致谢.

页:

<p:inputText onkeypress="onlyLetter(this)">
Run Code Online (Sandbox Code Playgroud)

功能:

function onlyLetter(input){
    $(input).keypress(function(ev) {
   var keyCode = window.event ? ev.keyCode : ev.which;
  //  code

    });
}
Run Code Online (Sandbox Code Playgroud)

Ash*_*nto 11

只需使用要禁用或阻止工作的键/数字的ascii代码(十进制值).ASCII表.

HTML:

<input id="inputTextBox" type="text" />
Run Code Online (Sandbox Code Playgroud)

jQuery:

$(document).ready(function(){
    $("#inputTextBox").keypress(function(event){
        var inputValue = event.which;
        // allow letters and whitespaces only.
        if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) { 
            event.preventDefault(); 
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

jsFiddle演示

  • 这是旧的,但我今天遇到了。您正在截断小写的y和z(121和122)。 (3认同)
  • 这是我上面的更新代码,以防止捕获sysmbols(!,@,#等).还退格并输入密钥启用.`if(!(inputValue> = 65 && inputValue <= 120)&&(inputValue!= 32 && inputValue!= 0)){event.preventDefault(); } https://jsfiddle.net/lucerosama/5x7td5bc/ (2认同)

VIJ*_*Y P 8

以下代码仅允许az,AZ和空格.

HTML

<input id="inputTextBox" type="text" />
Run Code Online (Sandbox Code Playgroud)

jQuery的

$(document).on('keypress', '#inputTextBox', function (event) {
    var regex = new RegExp("^[a-zA-Z ]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)


mar*_*are 6

首先,我对jQuery的了解很少,将提供一个普通的javascript示例。这里是:

document.getElementById('inputid').onkeypress=function(e){
    if(("abcdefghijklmnopqrstuvwxyz ").indexOf(String.fromCharCode(e.keyCode))===-1){
        e.preventDefault();
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Libin 那 nooowww 怎么样 (2认同)