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(); } });
target.selectionStart,target.selectionEndshow the beginning and end of the selected text in thetargetelement. 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