I have this javascript code, which, on desktop browsers works well to ensure the user can only enter characters 1 to 9.
However when testing in Chrome on Android, the keypad presented includes dash and period characters which the field accepts. 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:
<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 .
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">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.