简体   繁体   中英

mascara input javascript number with country

I need to put a mask in the field with javascript. example: +55 (11) 98888-0000 or +55 (11) 8888-0000.

I have a javascript function that works like this (11) 99999-9999 or (11) 9999-9999, I need to modify it to leave as above example. Here is the function code.

 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>Mascara Telefone</title> </head> <body> <html> <head> <title>Mascara Telefone</title> <script type="text/javascript"> /* Máscaras ER */ function mascara(o,f){ v_obj=o v_fun=f setTimeout("execmascara()",1) } function execmascara(){ v_obj.value=v_fun(v_obj.value) } function mtel(v){ v=v.replace(/\\D/g,""); // Removes all non-digit v=v.replace(/^(\\d{2})(\\d)/g,"($1) $2"); // Place parentheses around the first two digits v=v.replace(/(\\d)(\\d{4})$/,"$1-$2"); // Places hyphen between the fourth and fifth digits return v; } function id( el ){ return document.getElementById( el ); } window.onload = function(){ id('telefone').onkeyup = function(){ mascara( this, mtel ); } } </script> </head> <body> <input type="text" name="telefone" id="telefone" maxlength="15" /> </body> </html> </body> </html> 

you can specify a condition based on length of your text of input to the function

for +55 (11) 8888-0000 this use below exp v=v.replace(/^(\\d{2})(\\d{2})(\\d{4})(\\d)/g,"+"+"$1 ($2) $3-$4"); and max-lenth=18

for +55 (11) 98888-0000 use below exp v=v.replace(/^(\\d{2})(\\d{2})(\\d{5})(\\d)/g,"+"+"$1 ($2) $3-$4");and max-length=19

 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>Mascara Telefone</title> </head> <body> <html> <head> <title>Mascara Telefone</title> <script type="text/javascript"> /* Máscaras ER */ function mascara(o,f){ v_obj=o v_fun=f setTimeout("execmascara()",1) } function execmascara(){ v_obj.value=v_fun(v_obj.value) } function mtel(v){ v=v.replace(/\\D/g,""); // Removes all non-digit v=v.replace(/^(\\d{2})(\\d{2})(\\d{5})(\\d)/g,"+"+"$1 ($2) $3-$4"); return v; } function id( el ){ return document.getElementById( el ); } window.onload = function(){ id('telefone').onkeyup = function(){ mascara( this, mtel ); } } </script> </head> <body> <input type="text" name="telefone" id="telefone" maxlength="19" /> </body> </html> </body> </html> 

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