Keydown allowing numbers but not shift symbols on iPhone
Asked Answered
W

1

5

I have an event bound to an input that should only allow numbers. Simplified:

function (e) {
    if (-1 === [48,49,50,51,52,53,54,55,56,57].indexOf(e.keyCode)) {
        e.preventDefault();
    }
}

This works fine, but if someone types !, @, #, $, etc. the keyCode is still the same and the event default is not prevented.

On a physical keyboard, I can prevent this pretty simply by also checking e.shiftKey. However, on an iOS virtual keyboard, some of those characters exist (such as $) even for <input type=number> and they can be typed directly. Their keyCode is the same, but it seems like e.shiftKey is still falsey.

There are a variety of possible solutions that would be acceptable to me:

  • Have the virtual keyboard itself not display these characters (i.e. only display numbers and a period/decimal)
  • Detect that an invalid virtual key was pressed and suppress the event behavior
  • Determine the an invalid character will be added to the input's value and suppress the event behavior in this case
  • Others?
Whoopee answered 13/11, 2013 at 20:52 Comment(1)
Check if last character is bad and delete. No need for preventDefault.Gentes
Q
0

you can use <input type="tel" /> to limit the input to numbers in iOS -- although this also allows '*' and '#' to be typed, at least it's less work since you'd only have to check for those two characters

Querulous answered 14/11, 2013 at 21:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.