0

I have the following code to allow only numeric values to be entered in a form's input field:

HTML:

<input type="text" name="qtty" size="2" value="1" class="numOnly" />

Javascript:

var allowedKeys = [8, 9, 13, 27, 37, 39,
    48, 49, 50, 51, 52, 53, 54, 55, 56, 57
];
// 8 = backspace; 9 = tab; 13 = enter; 27 = escape; 37 = left; 39 = right;
// 48-57 = 0-9
$(".numOnly").keypress(function(event) {
    var charCode = (event.which) ? event.which : event.keyCode;
    if ($.inArray(charCode, allowedKeys) == -1)
        return false;
    else
        return true;
});

This works on the desktop (Chrome, Firefox) but not on Android (Chrome). On the latter some keystrokes including all alphanumerics (both upper and lower case) are passed on to the textbox, as well as some special characters (e.g. $, %) while other special characters (e.g. &, @) are not.

Why is this, an what can I do to make the above code work on mobile platforms as well?

Sushil
  • 2,837
  • 4
  • 21
  • 29
  • 1
    you can use `input type='number'` http://www.w3.org/TR/html-markup/input.number.html – Sushil Sep 08 '15 at 18:24
  • @Sushi: this does not explain why the quoted jQuery snippet behaves the way it does on Android. Also, type=number does not offer equivalent behavior, e.g. allows decimal points. – Frank van Wensveen Sep 09 '15 at 04:08
  • Possible duplicate of [How to allow only numeric (0-9) in HTML inputbox using jQuery?](https://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery) – emkey08 Jul 18 '19 at 08:17

1 Answers1

0

if you are like me and HATE decimal points use this:

$(".vinput").on("input change paste",
function filterNumericAndDecimal(event) {
    var formControl;
    formControl = $(event.target);
    var newtext = formControl.val().replace(/[^0-9]+/g, "");
    formControl.val(''); //without this the DOT will not go away on my phone!
    formControl.val(newtext);
});

if you need the dot included use [^0-9.] as regex

couple of things I found -keypress is not working on mobile .. -listening to keyup event is too late for calling preventDefault, but nevermind because preventDefault does not work on android ..

Jaxx0rr
  • 507
  • 4
  • 7