繁体   English   中英

在输入掩码中插入15个字符后的X.

[英]Insert X after 15 character in input mask

(XXX)XXX-XXXX xXXXX

我想在输入中的每个第15个字符后插入一个X符号。 我有一个商务电话输入框。 当用户键入并到达每个第15个字符时,jQuery将插入连字符(X)。

例如:(999)999-9999 x9999

我正在尝试一些代码,我认为我是如此接近正确的代码,但我有一些问题。 这是我的代码示例;

$(document).delegate('#businessPhone', 'keyup', function(e) {
        var Textlength = $(this).val();
console.log(Textlength.length);
        if (Textlength.length >= 14) {
            //alert("if"+Textlength.length);
            $("#businessPhone").mask("(999) 999-9999 x9999");
return false;
        } else {
            //alert("else"+Textlength.length);
$("#businessPhone").mask("(999) 999-9999");
        }
    });

如果用户完成输入所有字符,则代码正常工作。

但问题是如果字符长度达到14,用户想删除字符未删除的字符。

尝试这个

 $('#phone-number', '#example-form') .keydown(function (e) { var key = e.charCode || e.keyCode || 0; $phone = $(this); // Auto-format- do not expose the mask as the user begins to type if (key !== 8 && key !== 9) { if ($phone.val().length === 4) { $phone.val($phone.val() + ')'); } if ($phone.val().length === 5) { $phone.val($phone.val() + ' '); } if ($phone.val().length === 9) { $phone.val($phone.val() + '-'); } if ($phone.val().length === 15) { $phone.val($phone.val() + ' x'); } } // Allow numeric (and tab, backspace, delete) keys only return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105)); }) .bind('focus click', function () { $phone = $(this); if ($phone.val().length === 0) { $phone.val('('); } else { var val = $phone.val(); $phone.val('').val(val); // Ensure cursor remains at the end } }) .blur(function () { $phone = $(this); if ($phone.val() === '(') { $phone.val(''); } }); 
 <form id="example-form" name="my-form"> <label>Phone number:</label><br /> <!-- I used an input type of text here so browsers like Chrome do not display the spin box --> <input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX" /><br /><br /> <input type="button" value="Submit" /> </form> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM