raphael75
raphael75

Reputation: 3238

how to cancel keydown on mobile browsers

I have this which works perfectly on desktop browsers. It checks when the user presses a key in a zipcode text input field:

zip_field.addEventListener(
                    'keydown',
                    function(evt){check_zip({evt:evt, zip_field: zip_field, submit_button: submit_button})}, 
                    false
                    )

The check_zip function has this at the bottom to cancel the keypress if the user types a letter, etc.:

if(prevent_key)
{
    evt.preventDefault()
    evt.stopPropagation()
    return false;
}

On mobile browsers, the if statement is processed just like on the desktop browsers, but it still allows the character to go through. However, if I put breakpoints in and step through the code it works correctly!

I tested in Chrome and Firefox on Android and it happened on both. Is there something else I need to do on mobile to prevent/cancel the key and prevent it from appearing in the input box?

Update: I was able to test on iPhone and it is working correctly on there. So it's only broken on Android (FF, Chrome, and Samsung browser are all failing).

Upvotes: 3

Views: 2156

Answers (2)

raphael75
raphael75

Reputation: 3238

Well after creating a stripped down test page, I discovered that Chrome always interprets keys pressed using the Android keyboard as keyCode 229 in the keydown event. If I plugged my phone into my computer with the USB cable, keys I pressed on my desktop keyboard used the correct keycode, but the ones on the phone's virtual keyboard were all 229. After some more research I found this:

keyCode on android is always 229

However, I can't figure out why it works if I put breakpoints in and step through it.

Upvotes: 1

Takashi Harano
Takashi Harano

Reputation: 294

The way of access to evt is wrong. evt is passed to the parameter of check_zip() in object form in your code. Then you should access like this.

function check_zip(param) {
    ...
    if (prevent_key)
    {
        param.evt.preventDefault()
        param.evt.stopPropagation()
        return false;
    }
}

Upvotes: 0

Related Questions