0

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

1

2 Answers 2

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.

1
  • This is the exact behavior I want! Thank you. Commented Jul 23, 2024 at 16:20
0

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>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.