我有一个项目,我只想获取数字作为输入,所以我使用了一个类型为number的输入,但这也允许使用小数点分隔符等,我该如何防止使用,
、.
和e
。
我环顾四周,找不到一个能给出想要的结果的find,它们要么不阻止小数输入,要么允许用户仍然将其粘贴到字段中。
我有可以使用的javascript和jquery,但我不想使用外部库。
如果有人能帮助我,我将不胜感激。
function LimitKeys($id) {
$field = document.getElementById($id);
$value = $($field).val(); //if the value contains multiple e , or . the value is no longer valid and gives me blank
console.log($value);
$regex = /[^\d]/;
$val = $value.replace($regex, "");// cant replace in blank
console.log($val);
//$($field).val($val);
}
$('.number-only').keypress(function (event) { //sinds it's on keypress it won't catch the paste of data.
console.log(this.value);
var regex = new RegExp("^[0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
发布于 2016-11-08 22:16:28
试试这段代码
$(".number-only").on('input', function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$(".error").html("Only numbers allowed").show().fadeOut("slow");
return false;
}
});
别忘了创建一个错误类。
https://stackoverflow.com/questions/40489097
复制相似问题