[英]Prevent decimal place being entered into input field on mobile
I have this javascript code, which, on desktop browsers works well to ensure the user can only enter characters 1 to 9.我有这个 javascript 代码,它在桌面浏览器上运行良好,可以确保用户只能输入字符 1 到 9。
However when testing in Chrome on Android, the keypad presented includes dash and period characters which the field accepts.但是,在 Android 上的 Chrome 中进行测试时,显示的键盘包含字段接受的破折号和句点字符。 How can I prevent this?
我怎样才能防止这种情况?
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
UPDATE:更新:
This is how I am using the function in HTML:这就是我在 HTML 中使用该函数的方式:
<input type="number" class="form-control"
onkeypress="return isNumberKey(event)" />
I have another function to prevent being able to copy and paste non numeric chars into the code.我有另一个功能可以防止将非数字字符复制并粘贴到代码中。
$(document).ready(function() {
$('#number').bind("cut copy paste drag drop", function(e) {
e.preventDefault();
});
});
And if all else fails, there's server-side validation.如果一切都失败了,还有服务器端验证。
I really want to stop decimal places being possible on the front end.我真的很想在前端停止小数位。 Remember the character range I specified restricts this fine on a qwerty keyboard - however on android (and probably others) the number key pad allows entering
.
请记住,我指定的字符范围在 qwerty 键盘上限制了这一点 - 但是在 android(可能还有其他)上,数字键盘允许输入
.
and -
和
-
One possible solution:一种可能的解决方案:
<script> function onlyNumbers(num){ if ( /[^0-9]+/.test(num.value) ){ num.value = num.value.replace(/[^0-9]*/g,"") } } </script> <input type="text" onkeyup="onlyNumbers(this)">
尝试使用 HTML 属性 min 和 max 来设置数字的范围,并使用 type=number 来只允许数字。
Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.