我使用下面的jquery函数来格式化文本框值以创建类似于"(123)456-7890"的移动格式。
当我修改文本框值时,光标指向文本框的最后位置。
如何才能将其修复到应该存在的特定位置。
$("body").on("input propertychange", ".USMobileFormat", function (e) {
$(this).attr('maxlength', '14');
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57 || $(this).val().length >= 14)) {
return false;
}
var input = this.value.replace(/[^0-9\(\)\s\-]/g, "");
var inputlen = input.length;
// Get just the numbers in the input
var numbers = this.value.replace(/\D/g, '');
var numberslen = numbers.length;
// Value to store the masked input
var newval = "";
//Loop through the existing numbers and apply the mask
for (var i = 0; i < numberslen; i++) {
if (i == 0) newval = "(" + numbers[i];
else if (i == 3) newval += ") " + numbers[i];
else if (i == 6) newval += "-" + numbers[i];
else newval += numbers[i];
}
// Re-add the non-digit characters to the end of the input that the user entered and that match the mask.
if (inputlen >= 1 && numberslen == 0 && input[0] == "(") newval = "(";
else if (inputlen >= 6 && numberslen == 3 && input[4] == ")" && input[5] == " ") newval += ") ";
else if (inputlen >= 5 && numberslen == 3 && input[4] == ")") newval += ")";
else if (inputlen >= 6 && numberslen == 3 && input[5] == " ") newval += " ";
else if (inputlen >= 10 && numberslen == 6 && input[9] == "-") newval += "-";
var position = setTimeout(function () { doGetCaretPosition(this); }, 300);
$(this).val(newval.substring(0, 16));
setTimeout(function () { setCaretPosition(this, position); }, 300);
});
function doGetCaretPosition(ctrl) {
var CaretPos = 0;
if (ctrl.selectionStart || ctrl.selectionStart == 0) {// Standard.
CaretPos = ctrl.selectionStart;
}
else if (document.selection) {// Legacy IE
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
return (CaretPos);
}
function setCaretPosition(ctrl, pos) {
if (ctrl.setSelectionRange) {
ctrl.focus();
ctrl.setSelectionRange(pos, pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}