skip to Main Content

I have a basic HTML input field (for phone numbers), that currently lets the user type and submit whatever they want inside:

923-98-Ilovekittens :3

However, I want the field to look like this:

+1 (___)-___-____

And as the user types digits from 0-9, I want those gaps to be filled:

+1 (748)-55_-____

How do I accomplish this with Javascript (and if easier, a Javascript library)?

2

Answers


  1. I guess you can use some input mask library, like this one: https://imask.js.org/.

    The third example on their page might work for you.

    Login or Signup to reply.
  2. You can use an input mask library like Inputmask by including the Inputmask library in your HTML file

    <script 
    src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"> 
       </script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/inputmask/5.0.6- beta.0/jquery.inputmask.min.js"></script>
    

    And apply the input mask to the input field

        <input type="text" id="phone" placeholder="+1 (___)-___-____">
    
    <script>
      $(document).ready(function(){
        $("#phone").inputmask("+1 (999) 999-9999");
      });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search