简体   繁体   中英

Insert X after 15 character in input mask

(XXX) XXX-XXXX xXXXX

I want insert a X symbol after every 15th character in input. I have a Business Phone input box. When a user is typing and reaches each 15th character, then jQuery will insert a hyphen (X).

For example: (999) 999-9999 x9999

I'm trying some codes and i think i'm so close to correct code but i have some problems. Here is my code sample;

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

Code is working fine as aspected if user complete enter all characters.

But problem is user wants to remove characters the characters did not delete if character length reach 14 .

try this

 $('#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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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