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
How to accepts only character values in HTML5
提问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
回答by soyuka
回答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