Click here to Skip to main content
14,391,319 members
Rate this:
Please Sign up or sign in to vote.
Hi
I have a text to enter phone number.

when I give number 8888888888
it should be converted to (888)888-8888 this format.

How can I achieve this using javascript or jquery?
Posted
Updated 30-Oct-19 10:21am
Rate this:
Please Sign up or sign in to vote.

Solution 1

Here is clear cut solution

Masked Input[^]

Here is manual js: This works on onblur:

<script src="http://code.jquery.com/jquery-latest.min.js"
    <script type="text/javascript">
        function formatPhone(obj) {
            var numbers = obj.value.replace(/\D/g, ''),
        char = { 0: '(', 3: ') ', 6: ' - ' };
            obj.value = '';
            for (var i = 0; i < numbers.length; i++) {
                obj.value += (char[i] || '') + numbers[i];
            }
        }
    </script>

And HTMl Code:
<input type="text" name="test"  önblur="formatPhone(this);" />
   
v2
Comments
syna syna 8-Apr-14 8:52am
   
can I get any other solution without using MaskedInput.js?
Er. Puneet Goel 8-Apr-14 8:57am
   
yes you can. But using masking is much preferred. But still if you need, let me know?
syna syna 9-Apr-14 1:18am
   
yes i want in javascript i dont want to use Maskedinput js
Er. Puneet Goel 9-Apr-14 3:20am
   
I have modified the solution, please check and mark solution accordingly. Let me know if any issue is there?
Rate this:
Please Sign up or sign in to vote.

Solution 2

You can use regular expression, below link is having the solution of same issue.

http://stackoverflow.com/questions/2616395/regular-expression-with-mask[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100