juice juice - 1 year ago 114
jQuery Question

Integer numeric input only on mobile devices

I am using

<input type='text' onkeypress='return isNumberKey(event)'>

I have tried
<input type='number'>
but that allows people to use a period and 'e'. I only want people to be allowed to use non-negative integers only.

Ideally, I would like to make it so only the number keypad gets pulled up in Safari and Chrome (I believe the majority of mobile users only use these two browsers) but I'll definitely settle for allowing only being able to press non negative integers.

function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 8 && (charCode < 48 || charCode > 57))
return false;

return true;

Answer Source

You can use pattern attribute with RegExp [0-9] or [1-9], input event, RegExp.prototype.test(), String.prototype.slice() with parameter 0, -1 to remove last input value if not a digit which matches RegExp at pattern attribute

document.querySelector("input").addEventListener("input", function(event) {
  var value = event.target.value;
  if (!new RegExp(event.target.pattern).test(value)) {
    event.target.value = value.slice(0, -1)
<input type="number" pattern="[0-9]" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download