Search code examples
javascriptandroidcursorkeypad

How to insert hyphens into a phone number input?


I have a JavaScript which auto hyphen a user input on a text field for a phone number. It works find on iPhone but on android the hyphen show up and the cursor also get to the right place (after the hyphen) but when user type the number it display it before the hyphen?

What is this issue related to?

Here is my script:

if((input.value.length == 3) || (input.value.length == 7) {
    input.value = input.value + "-";
    input.setSelectionRange(input.value.length,input.value.length);
}

Solution

  • Try this:

    if((input.value.length == 3) || (input.value.length == 7)) {
      setTimeout(function() {
        input.value = input.value + "-";
        input.setSelectionRange(input.value.length,input.value.length);
      }, 10);
    }