如何使HTML输入标签只接受数值? [英] How to make HTML input tag only accept numerical values?
问题描述
我需要确保某个< input>
字段仅将数字作为值。
输入不是表格的一部分。因此它没有被提交,所以在提交期间验证不是一种选择。我希望用户无法输入数字以外的任何字符。
I need to make sure that a certain <input>
field only takes numbers as value.
The input is not part of a form. Hence it doesn't get submitted, so validating during submission is not an option. I want the user to be unable to type in any characters other than numbers.
有没有一种简单的方法可以实现这一点?
Is there a neat way to achieve this?
推荐答案
You can use HTML5 input type number to restrict only number entries:
<input type="number" name="someid" />
这仅适用于HTML5投诉浏览器。确保您的html文档的文档类型为:
This will work only in HTML5 complaint browser. Make sure your html document's doctype is:
<!DOCTYPE html>
另请参阅 https://github.com/jonstipe/number-polyfill在旧版浏览器中透明支持。
See also https://github.com/jonstipe/number-polyfill for transparent support in older browsers.
通常情况下,您可以使用JS验证,如下所示:
For general purpose, you can have JS validation as below:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>
如果您想允许小数点,用下面的代替if条件: $ b (charCode> 31&&(charCode!= 46&&(charCode< 48 || charCode> 57))
$ b
If you want to allow decimals replace the "if condition" with this:
if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))
Source: HTML text input allows only numeric input
JSFiddle演示: http://jsfiddle.net/viralpatel/nSjy7/
JSFiddle demo: http://jsfiddle.net/viralpatel/nSjy7/
这篇关于如何使HTML输入标签只接受数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!