自定义掩码函数不工作时,插入字符在中间Javascript/JQuery



我有一个函数:

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;
}

我在:

$(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);
});

这工作完美,但当我试图从字符串的中间删除一个数字,然后再次添加它,它追加到字符串的末尾,不坚持到当前位置。

的例子:

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

注意,它在string的末尾添加了number 8

任何帮助都是感激的,谢谢你

您应该使用keyup而不是keypress,因为在keypress上输入的值尚未改变,并且您在新值发布到输入之前应用您的过滤器。这就是为什么要添加新字符的原因。

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

这里的工作代码示例http://jsbin.com/upinux/1/edit

最新更新