什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
Praveen Jeganathan报道
不再有插件,jQuery在1.7版本中实现了自己的jQuery. isnumeric()。 参见:https://stackoverflow.com/a/20186188/66767
什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
Praveen Jeganathan报道
不再有插件,jQuery在1.7版本中实现了自己的jQuery. isnumeric()。 参见:https://stackoverflow.com/a/20186188/66767
当前回答
请在脚本底部添加:
if(this.value.length == 1 && this.value == 0)
this.value = "";
其他回答
检查数据库使用的查找代码:
function numonly(root){
>>var reet = root.value;
var arr1 = reet.length;
var ruut = reet.charAt(arr1-1);
>>>if (reet.length > 0){
var regex = /[0-9]|\./;
if (!ruut.match(regex)){
var reet = reet.slice(0, -1);
$(root).val(reet);
>>>>}
}
}
//Then use the even handler onkeyup='numonly(this)'
也允许负数
下面的代码也接受负数
HTML
<input type="text" name="myText" />
JS
var pastValue, pastSelectionStart, pastSelectionEnd;
$("input").on("keydown", function() {
pastValue = this.value;
pastSelectionStart = this.selectionStart;
pastSelectionEnd = this.selectionEnd;
}).on("input propertychange", function() {
if ( this.value.length > 0 && $.isNumeric(this.value) == false && this.value != '-' ) {
this.value = pastValue;
this.selectionStart = pastSelectionStart;
this.selectionEnd = pastSelectionEnd;
}
}).on('blur', function(){
if(this.value == '-')
this.value = '';
});
如果你使用的是HTML5,你就不需要花大力气去执行验证。只要用——
<input type="number" step="any" />
step属性允许小数点有效。
有一个很好的jquery插件叫做jquery Mask plugin,设计用于在表单字段和html元素上做蒙版,但你也可以用它来简单地定义什么类型的数据可以在字段中输入:
$('.numeric-input').mask('0#');
现在只有数字将被允许在您的表单字段。
请在脚本底部添加:
if(this.value.length == 1 && this.value == 0)
this.value = "";