javascript - Prevent input cursor from going to end of input after value replace on keyup -
i'm using function found here formatting input. works, problem when adding text input, caret automatically goes end of input, , doesn't allow adding other place of input not end.
how can prevent cursor/cursor going end of input on keyup?
function format(input, format, sep) { var output = ""; var idx = 0; (var = 0; < 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); });
Comments
Post a Comment