GGio
GGio

Reputation: 7653

Custom Mask Function does not work when inserting character in the middle Javascript/JQuery

I have a function:

function maskInput(input, location, delimiter, length) {
    //Get the delimiter positons
    var locs = location.split(',');

    //Iterate until all the delimiters are placed in the textbox
    for (var delimCount = 0; delimCount <= locs.length; delimCount++) {
        for (var inputCharCount = 0; inputCharCount <= input.length; inputCharCount++) {

            //Check for the actual position of the delimiter
            if (inputCharCount == locs[delimCount]) {

                //Confirm that the delimiter is not already present in that position
                if (input.substring(inputCharCount, inputCharCount + 1) != delimiter) {
                    input = input.substring(0, inputCharCount) + delimiter + input.substring(inputCharCount, input.length);
                }
            }
        }
    }

    input = input.length > length ? input.substring(0, length) : input;

    return input;
}

I use this in:

$(document).on('keypress paste drop blur', '#my_phone_number', function() {
    //remove any nondigit characters
    var myVal = $(this).val().toString().replace(/\D/g,'');
    $(this).val(myVal);


    var inVal   = maskInput(myVal, '3,7', '-', 12);

    $(this).val(inVal);
});

This works perfectly but when I try to remove a digit from the middle of string and then add it again it appends it to the end of string, does not stick to the current position.

Example:

 Entered String: '1234567890'
 After Mask Function Is Called: '123-456-7890'
 Number 5 removed and entered Number 8 instead of 5: '123-467-8908'

Note that it appended number 8 at the end of string.

Any help is appreciated, thank you

Upvotes: 1

Views: 350

Answers (1)

Vadim
Vadim

Reputation: 8789

You should use keyup instead of keypress, since on keypress the value of input is not yet changed and you apply your filter prior to new value is posted to input. That is the reason why new character is appended.

$(document).on('keyup paste drop blur', '#my_phone_number', function() {
    ...
});

Example of working code here http://jsbin.com/upinux/1/edit

Upvotes: 1

Related Questions