0

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);
});
Community
  • 1
  • 1
antigaprime
  • 79
  • 1
  • 9
  • There is a nice [plugin](http://digitalbush.com/projects/masked-input-plugin/) for masking inputs – andrew Feb 08 '16 at 21:48
  • @andrew Thanks, although I had already found it, and from the demos, keyboard arrow keys aren't allowed, so I'm not sure it's what I'm looking for. – antigaprime Feb 09 '16 at 01:02
  • @andrew Actually, after downloading the and testing the plugin, it turns out my previous comment was mistaken. If you put your response in an answer I'll mark it as correct. – antigaprime Feb 09 '16 at 02:09
  • I think that answers which recommend software are frowned upon since they don't contain code or a direct solution to the problem. Glad I was able to help though :) – andrew Feb 09 '16 at 04:58

0 Answers0