-1

So I have the following input:

<input type='text' placeholder='Phone number'>

Simple as can be. What I want is that whenever that specific box is focused, a pre-determined pattern will show up to assist the user on how exactly will that box accept the data. The way I want it to display is like this:

(__)____-____

So when the user has typed any 7 initial numbers, it'd display like this:

(21)3322-1___

without the user needing to type "(", ")", or "-", since that would already be in the correct spot while the user is typing the number.

After the box has accepted 10 digits (two in the beginning, then four - four), the input box will stop receiving any type of data (that could be done with maxlength='10', so not an issue). If no data is in the box, it'd go back to display the regular placeholder of the html file:

Phone number

I'd be glad if anyone teach me how to do this. Thanks in advance to anyone that's willing to help.

Kamals
  • 27
  • 2

1 Answers1

0

How about grouping inputs together and focusing the next one if the maximum input length has been reached?

let container = document.querySelector('.phone-input');

container.addEventListener('input', event => {
  let input = event.target;
  if (input.value.length >= input.attributes['maxlength'].value) {
    while ((input = input.nextElementSibling) !== null) {
      if (input.tagName === 'INPUT') {
        input.focus();
        break;
      }
    }
  }
});
<div class="phone-input">
 (<input type="text" maxlength="2" size="2">)
  <input type="text" maxlength="4" size="4"> -
  <input type="text" maxlength="4" size="4">
</div>

Implementation based on the answer to this question: Focus next input once reaching maxlength value

le_m
  • 19,302
  • 9
  • 64
  • 74
  • Hello, thanks for the answer. That actually didn't work for me, but this: http://jsfiddle.net/mgibsonbr/4m5fg/8/, which can be found as an answer in that same question you linked, worked for me just fine. It's an interesting idea, I'd +1 you but I need 15 reputation for that. – Kamals May 23 '16 at 23:28