(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>
关于javascript - 在输入掩码中的 15 个字符后插入 X,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36913743/