Home > Enterprise >  How to format phone number in javascript
How to format phone number in javascript

Time:01-07

I created a form field in html and I want to auto format the phone number input to look like (123) 456-7890.

my html code looks like this:

<form>
<div >
     <div >
      <input type="text" id="Phone" name="Phone" data-field-type="Phone"  placeholder="Phone" ><i ></i></div>
</div>
</form>

How do I write the JavaScript to format the phone number how I want?

CodePudding user response:

Using the function of this answer, you could achieve what you want by appending this in your script tag:

document.getElementById('Phone').addEventListener('focusout', function() {
    event.target.value = formatPhoneNumber(event.target.value);
});

You can also use the change event instead of focusout as IT goldman suggested.

CodePudding user response:

You can use below code as reference and change value as soon as number is input.

function RecordChange() {
    let number = document.getElementById("phone_number_field").value;
    //console.log(number);
    if(number.length > 10) {
        document.getElementById("Show_Warning").innerHTML = "invalid phone number"
        document.getElementById("phone_number_field").style.borderColor = 'red';
    }
    else {
        document.getElementById("Show_Warning").innerHTML = ""
        document.getElementById("phone_number_field").style.borderColor = 'black';
    }
    if(
        number.length === 10
    ) {
        let targetvalue = "("   number.slice(0, 3)   ")-"   number.slice(3, 7)   "-"   number.slice(7, 10)
        console.log(targetvalue);
        document.getElementById("phone_number_field").value = targetvalue;
    }
    
}
<html>
    <title>Header</title>
    <body>
        <script src="script.js"></script>
        Body Starts : 
        <div>
            <p>Phone Number : </p>
            <input type="text" id="phone_number_field" oninput="RecordChange()">
            <p id = "Show_Warning"></p>
        </div>
    </body>
</html>

This is just a dummy code, but function you can use for changing number format as required.

  • Related