javascript – How to set the cursor at the beginning of the mask when switching tabs?

Question:

In the form in the phone field I use a mask based on the Imask library.

  1. I'm trying to make it so that when both the mouse and the tab are focused, a full mask with brackets appears in the field, and the cursor is set to the initial input position. There is a problem here: either an incomplete mask appears, only +38, or the cursor moves to the end due to a taboo on the field
  2. I can't clear the phone field after submitting the form, I get

Warring: Element value was changed outside of mask. Syncronize mask using mask.updateValue() to work properly.

const phone = document.querySelector('.phone');
const name = document.querySelector('.name');

if (phone) {
  phone.onfocus = () => {
    newIMask(phone)
  }
}

function newIMask(phone) {
  let phoneMask = IMask(
    phone, {
      mask: '{+38} (000) 000-00-00',
      lazy: false
    });
  phone.value = phoneMask.unmaskedValue; //если закомментировать, то по табу курсор сместиться вконец
}

document.getElementById("form").addEventListener('submit', function(e) {
  e.preventDefault();
  phone.value = "";
  window.open('mailto:mail@example.com?name=' + name.value + '&body=' + phone.value);
});
<script src="https://unpkg.com/imask"></script>
<form id="form">
  <input type="text" name="name" class="name">
  <input type="tel" name="phone" class="phone">
  <input type="submit" value="Отправить">
  <form>

I receive this notification:

Element value was changed outside of mask. Syncronize mask using mask.updateValue() to work properly.

Answer:

I used phoneMask.alignCursor() to set the cursor to the "beginning" of the mask. I also just set phoneMask.value = "" to avoid the error message. It looks like everything is working as it should.

const form = document.querySelector("#form");
const nameInput = document.querySelector(".name");
const phoneInput = document.querySelector(".phone");

// Инициализируем iMask только один раз
const phoneMask = IMask(phoneInput, {
  mask: "{+38}` (000) 000-00-00",
  lazy: false,
});
phoneInput.addEventListener("focus", () => {
  // При фокусе выравниваем курсор
  phoneMask.alignCursor();
});

form.addEventListener("submit", event => {
  event.preventDefault();

  // Сначала используем значения
  window.open("mailto:mail@example.com?name=" + nameInput.value + "&body=" + phoneInput.value);
  // И уже потом очищаем их
  nameInput.value = "";
  phoneInput.value = "";
  phoneMask.value = "";
});
<script src="https://unpkg.com/imask"></script>
<form id="form">
  <input type="text" name="name" class="name">
  <input type="tel" name="phone" class="phone">
  <input type="submit" value="Отправить">
</form>
Scroll to Top