什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
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
当前回答
只需通过parseFloat()运行内容。它将在无效输入时返回NaN。
其他回答
只需通过parseFloat()运行内容。它将在无效输入时返回NaN。
你看不到字母的神奇出现和消失的关键下来。这也适用于鼠标粘贴。
$('#txtInt').bind('input propertychange', function () {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
不再有插件,jQuery在1.7版本中实现了自己的jQuery. isnumeric()。
jQuery。isNumeric(value) 确定其参数是否为数字。
样品结果
$.isNumeric( "-10" ); // true
$.isNumeric( 16 ); // true
$.isNumeric( 0xFF ); // true
$.isNumeric( "0xFF" ); // true
$.isNumeric( "8e5" ); // true (exponential notation string)
$.isNumeric( 3.1415 ); // true
$.isNumeric( +10 ); // true
$.isNumeric( 0144 ); // true (octal integer literal)
$.isNumeric( "" ); // false
$.isNumeric({}); // false (empty object)
$.isNumeric( NaN ); // false
$.isNumeric( null ); // false
$.isNumeric( true ); // false
$.isNumeric( Infinity ); // false
$.isNumeric( undefined ); // false
下面是如何将isNumeric()与事件侦听器绑定在一起的示例
$(document).on('keyup', '.numeric-only', function(event) {
var v = this.value;
if($.isNumeric(v) === false) {
//chop off the last char entered
this.value = this.value.slice(0,-1);
}
});
不需要长代码的数字输入限制,只是尝试这段代码。 它还接受有效的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 />
您可以通过添加模式对文本输入使用HTML5验证。不需要使用regex或keyCodes手动验证。
<input type="text" pattern="[0-9.]+" />
$("input[type=text][pattern]").on("input", function () {
if (!this.checkValidity())
this.value = this.value.slice(0, -1);
});
对于输入[type=number]的解决方案,请参阅我的完整答案