什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
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
当前回答
你可以使用带有number()方法的Validation插件。
$("#myform").validate({
rules: {
field: {
required: true,
number: true
}
}
});
其他回答
保持插入符号在输入中的位置的其他方法:
$(document).ready(function() {
$('.numbersOnly').on('input', function() {
var position = this.selectionStart - 1;
fixed = this.value.replace(/[^0-9\.]/g, ''); //remove all but number and .
if(fixed.charAt(0) === '.') //can't start with .
fixed = fixed.slice(1);
var pos = fixed.indexOf(".") + 1;
if(pos >= 0)
fixed = fixed.substr(0,pos) + fixed.slice(pos).replace('.', ''); //avoid more than one .
if (this.value !== fixed) {
this.value = fixed;
this.selectionStart = position;
this.selectionEnd = position;
}
});
});
优点:
用户可以使用方向键、退格键、删除键、… 当你想要粘贴数字的时候就可以了
Plunker:演示工作
不需要长代码的数字输入限制,只是尝试这段代码。 它还接受有效的int和float值。
Javascript方法
onload = function () { var ele = document.querySelectorAll('.number-only')[0]; 避署。Onkeypress =函数(e) { 如果(isNaN (this.value + " " + String.fromCharCode (e.charCode))) 返回错误; } 避署。Onpaste = function(e){ e.preventDefault (); } } <p>只接受有效的int和float值的输入框 <input class="number-only" type=text />
jQuery方法
$(函数(){ $ (' .number-only ') .keypress(函数(e) { if(isNaN(this.value+""+String.fromCharCode(e.charCode)))返回false; }) .on("剪切复制粘贴",函数(e){ e.preventDefault (); }); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <p>只接受有效的int和float值的输入框 <input class="number-only" type=text />
更新
上面的答案适用于最常见的用例——将输入验证为数字。
但是下面是特殊用例的代码片段
允许负数 在删除之前显示无效的击键。
$(function(){ $('.number-only').keyup(function(e) { if(this.value!='-') while(isNaN(this.value)) this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'') .split('').reverse().join(''); }) .on("cut copy paste",function(e){ e.preventDefault(); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> Input box that accepts only valid int and float values.</p> <input class="number-only" type=text />
jquery。数字插件也很适合我。
我唯一不喜欢的就是直觉。在没有任何反馈的情况下,按键被“禁止”,用户可能会变得偏执或怀疑他的键盘是否坏了。
我在插件中添加了第二个回调函数,使阻塞输入的简单反馈成为可能:
$('#someInput').numeric(
null, // default config
null, // no validation onblur callback
function(){
// for every blocked keypress:
$(this).effect("pulsate", { times:2 }, 100);
}
);
当然,这只是一个示例(使用jQuery UI)。任何简单的视觉反馈都有帮助。
最好的方法是在文本框失去焦点时检查它的上下文。
可以使用正则表达式检查内容是否为“数字”。
或者你也可以使用Validation插件,它基本上会自动完成。
如果你使用的是HTML5,你就不需要花大力气去执行验证。只要用——
<input type="number" step="any" />
step属性允许小数点有效。