Phone Number Formatting (Real-time)


Author: Vincent Berger
Created: Oct 14, 2018






Format the inserted number characters to a valid phone number format.
In this case the max length of the input should be 10 numbers. The formatting is done in real-time with a setInterval() method. this is not recommended to use setInterval() to output in real-time if you have a high amout of codes lines the code would be executed agian and agian.
The best way to not use the 'this' keyword method to provide real-time is to use an addEventListener().
In this case that should be the 'keyup' eventlistener.

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>
    <body>
        <h3>Convert to phonenumber format</h3>
        <input id="inp" placeholder="Enter Phone Number" type="tel" maxlength="10"/>
        <div id="output"></div>
    </body>
</html>
				

CSS:

body {
    margin:0px; text-align:center;
    background-color:lightblue;
}
h3 {
    color:white; position:relative; 
    top:20vh;
}
input {
    border:0px; outline:none;
    margin:0px; width:50vw;
    background-color:white;
    position:relative; top:25vh;
    width:140px; height:30px;
    border-radius:4px;
}
#output {
    position:relative; top:30vh; 
    font-size:20px; font-weight:700;
    color:white;
}
				

Javascript:

setI=setInterval(()=>{
var x=(arr,str,len,i)=>{
    len=str.length;
    for(i=0; i<len; i++){
        arr.push(str[i]);
        if(i==0){
            arr.unshift("(");
        }else if(i==2){
            arr.push(") ");
        }else if(i==5){
            arr.push("-");
        }
    }
    return arr;
}
$("#output").html(x([],$("#inp").val()));
},10);
				


Place a comment related to this article

!

When u want to use a code block in your comment, you need to work with the <pre> and <code> tags.
You can specify the program language you want to use in the comment to assign the code tag class attribute with your program language name.
<pre>
  <code class="javascript">
   //_ Use lowercase phrase within the code tags class attribute:
   //_ C++ refered as cpp
   //_ C# refered as cs
   //_ Objective-C and C both refered as c
   //_ VB.net refered as vbnet
   //_ And so on...
  </code>
</pre>
Available program languages:
  • Access log
  • Apache
  • AutoIt
  • Arduino
  • Bash
  • C
  • C#
  • C++
  • CSS
  • CoffeeScript
  • HTML or XML
  • JSON
  • Java
  • JavaScript
  • Nginx
  • Objective-C
  • PHP
  • Perl
  • Python
  • Ruby
  • SQL
  • Swift
  • PowerShell
  • VB.net
We do not allow any direct type of links in the comment section.
Please format a link with with the following query:
domain dot com/?q=query
Thank you for understanding.


3248fsdf1283 Captcha


Back to Top