<input type="tel"
       id="phone"
       name="phone"
       placeholder="(xxx) xxx-xxxx"
       />
body {
  font-family: "Open Sans", sans-serif;
  box-sizing: border-box;
}

input {
  display: inline-block;
  font-size: 18px;
  padding: 10px 10px !important;
  margin-top: 15px !important;
  margin-bottom: 15px !important;
  border: 1px solid #cdcdcd !important;
  outline: none;
}
const phone = document.getElementById("phone")


phone.oninput = (e) => {
  let cursorPos = e.target.selectionStart
  let formatInput = autoFormatPhoneNumber(e.target)
  e.target.value = String(formatInput)
  let isBackspace = (e?.data==null) ? true: false
  let nextCusPos = nextDigit(formatInput, cursorPos, isBackspace)
  
  phone.setSelectionRange(nextCusPos+1, nextCusPos+1);
}

// Functions

function nextDigit(input, cursorpos, isBackspace) {
  if (isBackspace){
    for (let i = cursorpos-1; i > 0; i--) {
    if(/\d/.test(input[i])){
      return i
    }
  }
  }else{
    for (let i = cursorpos-1; i < input.length; i++) {
    if(/\d/.test(input[i])){
      return i
    }
  }
  }
  
  return cursorpos
}

function autoFormatPhoneNumber(ref) {
  try {
    let phoneNumberString = ref.value
    var cleaned = ("" + phoneNumberString).replace(/\D/g, "");
    var match = cleaned.match(/^(\d{0,3})?(\d{0,3})?(\d{0,4})?/);
    return [match[1] ? "(": "",
            match[1], 
            match[2] ? ") ": "",
            match[2],
            match[3] ? "-": "",
            match[3]].join("")
    
  } catch(err) {
    return "";
  }
}

console.log(autoFormatPhoneNumber("2345678900")); // => "(234) 567-8900"
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.