Cleave.js: onKeyDown code not working on android mobile browsers

Created on 9 Jan 2017  路  10Comments  路  Source: nosir/cleave.js

Below code is not working properly on mobile browsers, the reason is event.keyCode or event.which is not returning proper value on mobile browser

 onKeyDown: function (event) {
            var owner = this, pps = owner.properties,
                charCode = event.which || event.keyCode;

            // hit backspace when last character is delimiter
            if (charCode === 8 && Cleave.Util.isDelimiter(owner.element.value.slice(-1), pps.delimiter, pps.delimiters)) {
                pps.backspace = true;

                return;
            }

            pps.backspace = false;
        },
bug

All 10 comments

Hey, can you please provide which mobile browser it happens?

Thanks, and maybe system version please.

Sorry, Chrome 55.0. 2882.91 and Android 6.0.1

Did a bit research for this one, seems it's an Android chrome browser issue. The keyup and keydown events always return key code 229 as a composition that buffers the user鈥檚 keystrokes.

Here are some discussion but no solution presented:

https://github.com/facebook/react/issues/6176
http://stackoverflow.com/questions/30743490/capture-keys-typed-on-android-virtual-keyboard-using-javascript
https://bugs.chromium.org/p/chromium/issues/detail?id=118639#c259

Let me know if anyone has an idea.

It worked using this hack:

    var owner = this,
      pps = owner.properties,
      charCode = event.which || event.keyCode;

    // hit backspace when last character is delimiter

    if (Util.isAndroid() &&
        event.target.value.length &&
        event.target.value.length === this._lastEventValue.length - 1 &&
        Util.isDelimiter(pps.result.slice(-1), pps.delimiter, pps.delimiters)
    ) {
      charCode = 8;
    }
    if (charCode === 8 &&
        Util.isDelimiter(pps.result.slice(-1), pps.delimiter, pps.delimiters)) {
      pps.backspace = true;
    } else {
      pps.backspace = false;
    }
    this._lastEventValue = event.target.value;

Thanks, @andrglo for sharing your hack. But you forgot to define the variable Util. I've added:

var owner = this,
          pps = owner.properties,
          Util = Cleave.Util, // this line
          charCode = event.which || event.keyCode;

And it works like a charm. :)

Fix PR merged, thanks guys.

I am still able to reproduce this issue with Cleave.js 0.7.17 on input[type=text] but not input[type=tel].

Just a friendly heads-up. I will just use the tel input type for now, to get around the issue.

Can anyone help how to write this code..

function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if ((charCode < 48 || charCode > 57))
return false;
return true;
};

Was this page helpful?
0 / 5 - 0 ratings