簡體   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