Home > Software engineering >  HTML onkeypress works in HTML but not through JavaScript function on iOS
HTML onkeypress works in HTML but not through JavaScript function on iOS

Time:01-23

I have an input field which I want to restrict to only input numbers. type="number" works fine on computer and my android mobile but fails on iOS and I can still enter text in it. I looked around online and found this solution for the input field:

<input onkeypress="return event.charCode >= 48 && event.charCode <= 57" id="priceInput" type="text">

It works on all devices I have tried so far. However, I want to use this code for many input fields, and also do more things when pressing on a key in those input field. Therefore I want to run it as a JavaScript function in a separate file. I found this answer which looked promising and worked for android and desktop:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
<input type="text" onkeypress="return isNumber(event)" />

However, this still fails on iOS and I can still put in all characters.

Questions

  1. How can I limit input field to only accept numbers on iOS phones?
  2. Do iOS have some blocker for functions to run on onkeypress?

CodePudding user response:

The snippet you find is quite old and uses the which and keyCode properties, which both are deprecated.

Instead use the code and / or key properties to determine which keyboard button has been pressed.

Note: with this method you'll have to whitelist every key that you want to be enabled for the input.

Since you're using a text input, consider using the inputmode attribute to force mobile users to use a specific keyboard, like a numeric keyboard which presents numbers.

const input = document.querySelector('input');
input.addEventListener('keydown', isNumber);

const allowedKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'Backspace'];

function isNumber(event) {
  if (!allowedKeys.includes(event.key)) {
    event.preventDefault();
  }
}
<input type="text" inputmode="numeric" />

Edit: alternatively you could use the input event which is triggered based on changes in the value of the input. This event will fire regardless the manner of input (keyboard, mouse, etc.). The snippet below will replace anything that is not a number with an empty string while typing.

const input = document.querySelector('input');
input.addEventListener('input', isNumber);

function isNumber(event) {
  event.target.value = event.target.value.replace(/[^0-9]/g, '');
}
<input type="text" inputmode="numeric" />

CodePudding user response:

function isNumber(e) {
    event = e.value;
if(event = ""){

console.log("empty") }

    return true;
}
<input type="text" onkeypress="return isNumber(event)" />
  • Related