setSelectionRange workaround doesn't work for

2019-08-13 16:54发布

I am trying to mask the phone number as the user types. I have used the javascript code below with jquery and the setTimeout workaround successfully on android 2.x devices, but I have not found a workaround for that works for android 4.0.3.

if (navigator.userAgent.toLowerCase().indexOf("android") >= 0) {
$.fn.usphone = function() {
    this.keyup(function(e) {
        // do not process del, backspace, escape, arrow left and arrow right characters
        var k = e.which;
        if (k == 8 || k == 46 || k == 27 || k == 37 || k == 39)
            return;
        // remove invalid characters
        var value = "";
        for (var i = 0; i < this.value.length; i++) {
            var ch = this.value[i];
            if (ch >= "0" && ch <= "9")
                value += ch;
        }
        // remove extra characters
        if (value.length > 10)
            value = value.substring(0, 10);
        // insert formatting characters
        if (value.length >= 3)
            value = "(" + value.substring(0, 3) + ")" + value.substring(3);
        if (value.length > 5)
            value = value.substring(0, 5) + " " + value.substring(5);
        if (value.length > 9)
            value = value.substring(0, 9) + "-" + value.substring(9);
        // set new value
        var $this = this;
        var length = value.length;
        setTimeout(function() {
            $this.value = value;
            $this.setSelectionRange(length, length);
        }, 0);
    });
};

$('#contact_edit_page, #contact_new_page, #callback_create, #callback_edit, #new_phonecall_contact_page, #new_phonecall').live('pagecreate', function() {
    $('[type^="tel"]').usphone();
});

}

1条回答
Root(大扎)
2楼-- · 2019-08-13 17:27

I just met the same problem. My solution is as follows,

.input {
  -webkit-user-modify: read-write;
}

It works in android 4.0.3 in my HTC.

查看更多
登录 后发表回答