Click here to Skip to main content
15,885,918 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 9:21am

Here is clear cut solution

Masked Input[^]

Here is manual js: This works on onblur:

JavaScript
<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:
HTML
<input type="text" name="test"  önblur="formatPhone(this);" />
 
Share this answer
 
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?
You can use regular expression, below link is having the solution of same issue.

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

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900