Link to home
Start Free TrialLog in
Avatar of ITsolutionWizard
ITsolutionWizardFlag for United States of America

asked on

onkeypress js phone number

hi i am looking for onkeypress javascript code for <input> just want mask phone like (xxx)xxx-xxxx
Avatar of Mrunal
Mrunal
Flag of India image

Hi
I will prefer use call convert JavaScript function on lost focus (i.e. on blur event of that textbox) So that after complete value entered you can format it.
See below code:
HTML:
<input type="text" id="txtPhone" />

JS Code:
var myInput = document.getElementById('txtPhone');
        myInput.addEventListener("blur", ConvertToUSPhone);
        
        function ConvertToUSPhone() {
            var newValue = myInput.value;
            var USNumber = newValue.match(/(\d{3})(\d{3})(\d{4})/);
            USNumber = "(" + USNumber[1] + ")" + USNumber[2] + "-" + USNumber[3];
            alert(USNumber);
        }

Open in new window

use this plugin : https://github.com/digitalBush/jquery.maskedinput

$("#phoneID").mask("(999) 999-9999");

Open in new window


<input id="phoneID" type="text" ..

Open in new window


also what about HTML5 ?
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/tel

<input type="tel" pattern="([0-9]{3}) [0-9]{3}-[0-9]{4}" name="phone" />

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of lenamtl
lenamtl
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial