javascript 如何在 HTML5 中只接受字符值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15411636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:42:26  来源:igfitidea点击:

How to accepts only character values in HTML5

javascripthtml

提问by PeterS

Is there any simple way I can use to prevent user from accepting numeric values in html textbox? I've encountered some features of HTML5 like type="email" etc...

有什么简单的方法可以用来防止用户接受 html 文本框中的数值?我遇到过一些 HTML5 的特性,比如 type="email" 等等......

Now is there any feature for accepting only character values?

现在是否有任何仅接受字符值的功能?

回答by Jeremy French

I don't know how well supported it is but the patternattribute should allow you to do this.

我不知道它有多受支持,但模式属性应该允许你这样做。

<input name="test" type="text" pattern="[A-Za-z]+">

回答by soyuka

I would do like that with jQuery :

我想用 jQuery 做到这一点:

JQuery

查询

$("#only-text").on('keyup', function(e) {
    var val = $(this).val();
   if (val.match(/[^a-zA-Z]/g)) {
       $(this).val(val.replace(/[^a-zA-Z]/g, ''));
   }
});

See the working fiddle.

请参阅工作小提琴

回答by Gatekeeper

If you want to restrict characters that can be typed into your inputs, you will have to use some Javascript to do so, example with jQuery can be found here

如果您想限制可以输入到输入中的字符,则必须使用一些 Javascript 来执行此操作,可以在此处找到使用 jQuery 的示例

With plain JS you could do something like

使用普通的 JS 你可以做类似的事情

document.getElementById("alphaonly").onkeypress=function(e){ 
var e=window.event || e 
var keyunicode=e.charCode || e.keyCode 
return (keyunicode>=65 && keyunicode<=122 || keyunicode==8 || keyunicode==32)? true : false 
} 

where "alphaonly" is id of your input

其中“alphaonly”是您输入的ID