3

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).

raphael75
  • 2,982
  • 4
  • 29
  • 44

2 Answers2

1

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.

raphael75
  • 2,982
  • 4
  • 29
  • 44
0

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;
    }
}
Takashi Harano
  • 294
  • 1
  • 3
  • 10
  • How do you know that the OP did not initialise `evt` correctly? That part of the code is not in their question... – trincot Oct 22 '18 at 15:31
  • I thought it from the parameter's form. But if a local variable evt is defined in this function, this shall not apply to. – Takashi Harano Oct 22 '18 at 15:42
  • If I console.log the event (evt) on Android browsers, it shows all the exact same things in the desktop browsers and iphone do. It behaves exactly the same way, it just doesn't prevent the key from displaying in the textbox (unless I put a breakpoint in). – raphael75 Oct 22 '18 at 17:34