How to give space in between number in input just for displaying?

I want to give space in between number just for displaying like this enter image description here

I used

phone.addEventListener("keyup", function(){
  if (txt.length==3 || txt.length==7)
    this.value=this.value+" "; 

but this code is working only for input type text, the problem with this is, the length of the input is not considering as 10.

enter image description here.

Is there any solution, with which it will be displayed with spaces, the length must be 10, and with type number, and in back-end it should be saved without spaces?


Example solution using the pattern input type with simple regexp that ensures only numbers, correct spacing, and submits only numbers without spaces to the server.

Your code does breaks down if the user inputs spaces themselves, so the JavaScript has been enhanced to ensure the correct format.

  1. Ignore the input of spaces and any input beyond 12 characters by preventing the default behavior (ignore the keystroke):

if ((txt.length == 12 || e.which == 32) & e.which !== 8) e.preventDefault();

(Literally “if 12 characters OR keypress is spacebar AND key is not the backspace key” then ignore the keypress)

  1. Add spaces automatically (as your code did): if ((txt.length == 3 || txt.length == 7) && e.which !== 8)...

NOTE: in both cases, if the backspace key is pressed, then allow that key to work (keycode 8).

  1. When the form is submitted, remove any spaces from the “phone” input so the server only receives the numbers.

document.getElementById("phone").addEventListener("keydown", function(e) {
  const txt = this.value;
  // prevent more than 12 characters, ignore the spacebar, allow the backspace
  if ((txt.length == 12 || e.which == 32) & e.which !== 8) e.preventDefault();
  // add spaces after 3 & 7 characters, allow the backspace
  if ((txt.length == 3 || txt.length == 7) && e.which !== 8)
    this.value = this.value + " ";
// when the form is submitted, remove the spaces
document.forms[0].addEventListener("submit", e => {
  const phone =["phone"];
  phone.value = phone.value.replaceAll(" ", "");
  <input id="phone" name="phone" type="pattern" placeholder="### ### ####" pattern="[d]{3} [d]{3} [d]{4}">
  <input type="submit">