<分区>
我有一个项目,我只想获取数字作为输入,所以我使用的是数字类型的输入,但这也允许使用小数点分隔符等。我如何防止使用 ,
.
和 e
.
我环顾四周,找不到能提供所需结果的,因为他们要么没有阻止小数输入,要么允许用户仍然将其粘贴到字段中。
我有可以使用的 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;
}
});