4

i'm trying to limit the input of a text input to only numbers. I have an event handler set up for jquery keydown() that can be seen below. It works as expected on the desktop browsers i've tested and also in mobile safari and chrome on iOS. But i'm experiencing a few issues in chrome on the Nexus 7.

function keyDownHandler( e ) {

    e.stopImmediatePropagation();

    if( !e.shiftKey && !e.altKey && !e.ctrlKey ) {

        var key = e.which || e.keyCode;

        if( key >= 48 && key <= 57 || 
            key >= 96 && key <= 105 || 
            key == 8 || key == 9 ||
            key == 37 || key == 39 ||
            key == 46 || key == 45 ) {

            return true;
        }

        if( key == 13 ) {
            //returned pressed, do something
        }
    }

    e.preventDefault();

    return false;
};

There appears to be few known bugs related to the android soft keyboard, whereby the same value for keycode is returned for every key. This value also varies depending on device, but for the nexus 7 it's 229. The numerical keys also intermittently return the correct value for keycode, which is nice. I should be able to just add some catch all logic to deal with this, but the issue i'm stuck on is that, even though this method returns false and calls e.preventDefault(), it's not preventing the characters appearing in the text input?

Am i doing something wrong and need to call something else to cancel the event on android chrome or is this a bug?

Just to note, it works fine in firefox and dolphin on the Nexus 7, just not chrome or opera, where the same issue occurs.

Thanks.

james
  • 4,150
  • 2
  • 30
  • 36
  • 1
    Given that (so far as I know) these browsers support `input type="number"`, why not use these and fall back to the text entry-restrictions if the `input`'s type defaults back to `text`? – David Thomas Nov 04 '12 at 17:52
  • thanks David. I had a look at input type='number' but the implementation across different browsers differs and some still allow a user to actually input non-numeric characters? So some sort of validation is still required – james Jan 29 '13 at 17:32
  • Possible duplicate of [jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)](https://stackoverflow.com/questions/891696/jquery-what-is-the-best-way-to-restrict-number-only-input-for-textboxes-all) – Harry B Apr 06 '18 at 21:29

0 Answers0