简体   繁体   中英

How can I format phone numbers or add a specific mask on a <span> or none-editable HTML elements?

I have a website where I allow visitors to login via their mobile phones. Their numbers are stored without formatting in the Database.

How can I format their numbers when displaying it within an HTML element? I want the user to see; for example; "You are logged in using +1-541-754-3010" instead of 15417543010.

I search here and there but all the solutions which I found for masking input fields when entering data and not when retrieving it.

With jQuery you can do a function for that

in the function first validate the size of the number, then convert it to an array then apply format to each group of numbers and pass them to an auxiliary array and return value.

 $(function(){ $('input').keyup(function(){ phoneFormat($(this).val()) }) }) function phoneFormat(number){ if(number.length == 11){ var array = number.split(''); var auxArray = [] auxArray[0] = '+'+array[0] auxArray[1] = '-'+array[1]+array[2]+array[3] auxArray[2] = '-'+array[4]+array[5]+array[6] auxArray[3] = '-'+array[7]+array[8]+array[9]+array[10] number = auxArray.join("") $('span').text(number); }else{ $('span').text("") } } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <input maxlength="11" type="text"> </div> You are logged in using: <span></span> 

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