简体   繁体   中英

Put dash after every n character with country code +1 during input from keyboard

 $('.creditCardText').keyup(function() { var foo = $(this).val().split("-").join(""); // remove hyphens if (foo.length > 0) { foo = foo.match(new RegExp('.{1,4}', 'g')).join("-"); } $(this).val(foo); });

I found this tutorial on putting dash after every 4 character from here my question is what if the character interval is not constant like in this example it is only after every 4 what if the interval is 3 characters "-" 3 characters "-" 4 characters so it would appear like this +1 123-123-1234 with country code +1.

I found this solution using an if else statement.

 function autoDash(f) { length = f.value.length; if(length<1){ f.value="+1-"+f.value; } else if(length == 6){ f.value=f.value+"-"; } else if(length == 10){ f.value=f.value+"-"; } }
 <input type="text" id="tel" name="tel" maxlength="15" onkeydown="autoDash(this)" />

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