In the form in the phone field, I use a mask based on the Imask library.
- I am trying to make it when focusing with both the mouse or the tab on the field, a full mask with brackets appears, and the cursor is set to the initial input position. There is a problem here: either an incomplete mask appears, or only +38, or the cursor moves to the end due to a taboo on the field.
- I can't clear the phone field after submitting the form, I get warning:
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');
const form = document.querySelector('#form');
if (phone) {
phone.onfocus = () => {
newIMask(phone)
}
form.addEventListener('keydown', function(e) {
if (e.key == 'Tab') {
if (phone.value === '') {
let tabMask = IMask(
phone, {
mask: '+38( 000) 000-00-00',
lazy: false
});
}
}
});
}
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>
UPD With this insertion of the code, I sort of solve the issue with the tab
const form = document.querySelector('#form');
form.addEventListener('keydown', function (e) {
if(e.key == 'Tab') {
if(phone.value === '') {
let tabMask = IMask(
phone, {
mask: '+38( 000) 000-00-00',
lazy: false
});
}
}
});
but each digit is entered with a warring:
Warring: Element value was changed outside of mask. Syncronize mask using mask.updateValue() to work properly.
and the phone field is not cleared when sending.
Could you help me with finding the right solution?
from How to position the cursor at the beginning of the mask when pushing tab key?
No comments:
Post a Comment