限制为数值而不是整数值
如何将输入字段限制为数值而不是整数值?限制为数值而不是整数值
<input type="text" class="numericOnly">
JQ
$(".numericOnly").keypress(function (e) {
if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});
如果你想允许小数点,将它们添加到字符类你正在使用。例如。 /[^0-9.]/g
如果您的语言环境中的小数点是.
,或者/[^0-9,]/g
如果它是,
(因为它在某些情况下)。
当然,这会让别人输入.0.0.0.1
,你需要对字段进行全值检查以及按键级检查。
另外,请记住,除了打字(例如粘贴)之外,还有很多方法可以进入字段(比如粘贴),所以(再次)在某个阶段进行全值检查将是一个好主意。
边注:使用e.which
,不e.keyCode
。 jQuery normalizes the event object,在没有本地设置的浏览器上设置e.which
。
感谢您的额外信息。你的建议完美。 – Fergoso 2014-09-26 11:11:07
带点
得到这个js文件
http://thefitties.co.uk/js/plugins/jquery-numeric.js
而且
在HTML
<input class="numeric" type="text">
在脚本
$("input.numeric").numeric()
WITHOUT点
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
OR
试试这个
$(".numericOnly").keypress(function(e) {
var code = e.which;
if(($(this).val().indexOf(".") == -1 && code == 46) || (code >= 48 && code <= 57) || (code == 51) || (code == 8) || (code >= 37 && code <= 40))
{
return true;
}
return false;
})
.bind("paste",function(e) {
e.preventDefault();
});
谢谢。你的建议工作得很好。 – Fergoso 2014-09-26 11:18:41
你应该在这里找到十进制值的正则表达式; O)http://stackoverflow.com/a/15134885/1370442 – bUKaneer 2014-09-26 10:54:25
为什么不ü尝试.isNumeric()函数检查...? – DeDevelopers 2014-09-26 10:55:33
http://api.jquery.com/jquery.isnumeric/ – Rorschach 2014-09-26 10:58:09