Mask only for the phone, moving the cursor to the beginning of the input, how to do?
-
Hello everyone.
Found a simple mask script for the phone, only needed for the phone, did not download large files, where there are different masks.
We need a slight modification of the mask, if you put the cursor when we enter the imput in the field, then you can put a dotted line at the very end, and how to make it to the beginning of the parenthesis +7 (
Modify so that it was impossible to put a dotted line at the end +7 (___) ___-_____ | , well, or if put, then threw to the beginning of the parentheses where we enter.
Well, or do so, press and +7 appears and then we write and the brackets themselves (___) are substituted, so do not put a dotted line at the end, because the beginning will go from +7.
Working scheme
https://jsfiddle.net/7reby9w6/1/JavaScript Anonymous, Feb 2, 2019 -
is it okay?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input id="inputPhone" value="+7(___)___-__-__" >
<script>
let inputPhone=document.getElementById("inputPhone");
inputPhone.oninput=()=>phoneMask(inputPhone)
function phoneMask(inputEl) {
let patStringArr = "+7(___)___-__-__".split('');
let arrPush = [3, 4, 5, 7, 8, 9, 11, 12, 14, 15]
let val = inputEl.value;
let arr = val.replace(/\D+/g, "").split('').splice(1);
let n;
let ni;
arr.forEach((s, i) => {
n = arrPush[i];
patStringArr[n] = s
ni = i
});
arr.length < 10 ? inputEl.style.color = 'red' : inputEl.style.color = 'green';
inputEl.value = patStringArr.join('');
n ? inputEl.setSelectionRange(n + 1, n + 1) : inputEl.setSelectionRange(17, 17)
}
</script>
</body>
</html>Cora Chavez
1 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!