I'm using the function found here for formatting an input. It works, the only problem is that when adding text to the input, the caret automatically goes to the end of the input, and doesn't allow adding anything to any other place of the input that is not the end.
How can I prevent the cursor/cursor from going to the end of the input on keyup
?
function format(input, format, sep) {
var output = "";
var idx = 0;
for (var i = 0; i < format.length && idx < input.length; i++) {
output += input.substr(idx, format[i]);
if (idx + format[i] < input.length) output += sep;
idx += format[i];
}
output += input.substr(idx);
return output;
}
$('.phoneinput').keypress( function(e){
var phoneLength = $(this).val();
phoneLength = phoneLength.replace(/[^\d]/g,'').length;
if (phoneLength == 10) {
e.preventDefault();
}
});
$('.phoneinput').keyup(function(e) {
var phoneNumber = $(this).val().replace(/-/g, "");
if (phoneNumber.length <= 10) {
phoneNumber = format(phoneNumber, [2, 4], "-");
}
$(this).val(phoneNumber);
});