There is a phone input field by mask +7(___) ___-__-__ , sometimes the user starts to enter the second digit 8 and then the number is written incorrectly. How can you not print the first character if it is 8?

Solved the problem:

 function getCaretPos(input) { if (input.createTextRange) { var range = document.selection.createRange.duplicate(); range.moveStart('character', -input.value.length); return range.text.length; } else { return input.selectionStart; } } $(".personal-phone").on("keydown", function(e){ var val = $(this).val(); var char = e.keyCode; var pos = getCaretPos(this); if (char == 104 && pos == 3) { e.preventDefault(); } }); 
  • And if he enters the second digit 7? And all the others? - Nick Volynkin
  • @NickVolynkin I would like to understand the principle, and I would complete the check for the remaining characters myself. - Nikolay
  • one
    Put keypress event handlers, check which digit is dialed, in what position. If you do not like - cancel the event. As if no one pressed on the keyboard. Take a lesson learn.javascript.ru/keyboard-events There is an example of canceling input - Sergey
  • one
    target.selectionStart , target.selectionEnd show the beginning and end of the selected text in the target element. In addition, they indicate the position of the caret when entering (where the character will be inserted). In this case, they are equal. Accept values ​​from 0 - the carriage at the beginning of the line, 1 - after the first character, etc. to the end of the line - Sergey
  • one
    @Sergey, thanks! Solved the problem. - Nikolay

1 answer 1

why don't you use the chartAt function?

if yourString.charAt(0) == 8 {function deleteFirstStmbol()}

  • one
    because the s[0] === s.charAt(0) already available for a long time: s[0] === s.charAt(0) - Grundy
  • and how does the deleteFirstStmbol () function work? - Nikolay
  • I wrote for example, depending on the logic of the code, it searches for and deletes the first character in the string. Here is how I implemented it: var str = "Вот такая строка"; function deleteFirstStmbol ( string ) { return string.slice(0,1); } console.log(deleteFirstStmbol(str)); var str = "Вот такая строка"; function deleteFirstStmbol ( string ) { return string.slice(0,1); } console.log(deleteFirstStmbol(str)); - spectre_it
  • Your method does not quite fit, solved the problem, added a description - Nikolay