在输入掩码中输入15个字符后插入X
问题描述:
(XXX)XXX-XXXX xXXXX在输入掩码中输入15个字符后插入X
我想在输入中的每个第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')
\t .keydown(function (e) {
\t \t var key = e.charCode || e.keyCode || 0;
\t \t $phone = $(this);
\t \t // Auto-format- do not expose the mask as the user begins to type
\t \t if (key !== 8 && key !== 9) {
\t \t \t if ($phone.val().length === 4) {
\t \t \t \t $phone.val($phone.val() + ')');
\t \t \t }
\t \t \t if ($phone.val().length === 5) {
\t \t \t \t $phone.val($phone.val() + ' ');
\t \t \t } \t \t \t
\t \t \t if ($phone.val().length === 9) {
\t \t \t \t $phone.val($phone.val() + '-');
\t \t \t }
if ($phone.val().length === 15) {
\t \t \t \t $phone.val($phone.val() + ' x');
\t \t \t }
\t \t }
\t \t // Allow numeric (and tab, backspace, delete) keys only
\t \t return (key == 8 ||
\t \t \t \t key == 9 ||
\t \t \t \t key == 46 ||
\t \t \t \t (key >= 48 && key <= 57) ||
\t \t \t \t (key >= 96 && key <= 105)); \t
\t })
\t
\t .bind('focus click', function() {
\t \t $phone = $(this);
\t \t
\t \t if ($phone.val().length === 0) {
\t \t \t $phone.val('(');
\t \t }
\t \t else {
\t \t \t var val = $phone.val();
\t \t \t $phone.val('').val(val); // Ensure cursor remains at the end
\t \t }
\t })
\t
\t .blur(function() {
\t \t $phone = $(this);
\t \t
\t \t if ($phone.val() === '(') {
\t \t \t $phone.val('');
\t \t }
\t });
<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>
在控制台我得到'类型错误:$(...)面具不是function'是否包含了'.mask什么库() '功能? – Jer
请参阅[http://jsfiddle.net/mykisscool/VpNMA/](http://jsfiddle.net/mykisscool/VpNMA/) –
@ sachin-k如果maxLength在html中设置为14,那么问题在这里将会不被触动,对吧?既然他想在每个第15个字符 – SSchneid