Javascript 只允许在文本框中输入数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7295843/
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
Allow only numbers to be typed in a textbox
提问by EnexoOnoma
How to allow only numbers to be written in this textbox ?
如何只允许在此文本框中写入数字?
<input type="text" class="textfield" value="" id="extra7" name="extra7">
回答by Darin Dimitrov
You could subscribe for the onkeypress event:
您可以订阅 onkeypress 事件:
<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />
and then define the isNumber
function:
然后定义isNumber
函数:
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
You can see it in action here.
回答by powtac
With HTML5 you can do
使用 HTML5,您可以做到
<input type="number">
You can also use a regex pattern to limit the input text.
您还可以使用正则表达式模式来限制输入文本。
<input type="text" pattern="^[0-9]*$" />
回答by Arnout Engelen
You also can use some HTML5 attributes, some browsers might already take advantage of them (type="number" min="0"
).
您还可以使用一些 HTML5 属性,某些浏览器可能已经利用了它们 ( type="number" min="0"
)。
Whatever you do, remember to re-check your inputs on the server side: you can never assume the client-side validation has been performed.
无论您做什么,请记住在服务器端重新检查您的输入:您永远不能假设已经执行了客户端验证。