diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..722d5e7 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.vscode diff --git a/phoneinput.js b/phoneinput.js index c6f83ce..1eee883 100644 --- a/phoneinput.js +++ b/phoneinput.js @@ -28,11 +28,16 @@ document.addEventListener("DOMContentLoaded", function () { formattedInputValue = ""; if (!inputNumbersValue) { - return input.value = ""; + return input.value = (e.data == "+") ? "+" : ""; } if (input.value.length != selectionStart) { // Editing in the middle of input, not last symbol + if (input.value[0] != '+'){ // Add "+" if input value startswith not "+" + var oldSelectionStart = input.selectionStart + input.value = '+' + input.value; + input.selectionStart = input.selectionEnd = oldSelectionStart + 1 + } if (e.data && /\D/g.test(e.data)) { // Attempt to input non-numeric symbol input.value = inputNumbersValue; @@ -62,10 +67,22 @@ document.addEventListener("DOMContentLoaded", function () { input.value = formattedInputValue; } var onPhoneKeyDown = function (e) { - // Clear input after remove last symbol var inputValue = e.target.value.replace(/\D/g, ''); if (e.keyCode == 8 && inputValue.length == 1) { + // Clear input after remove last symbol e.target.value = ""; + } else if ([8, 46].indexOf(e.keyCode) > -1 && inputValue.length > 1) { + // Prevent when removing service symbols + var symToClear + switch (e.keyCode) { + case 8: // BackSpace key + symToClear = e.target.value[e.target.selectionStart - 1]; + break; + case 46: // Delete key + symToClear = e.target.value[e.target.selectionStart]; + break; + } + if (symToClear && /\D/.test(symToClear)) e.preventDefault(); } } for (var phoneInput of phoneInputs) {