Pages

Search

Friday, February 20, 2009

Phone number formatting using javascript

Web sites which do give option for phone number should follow an universal format of arranging text boxes in an order like country code – STD – Line number.

I would like to create a html page that has 3 text boxes prompting for Country code, STD and Line number.






I am using 2 javascript functions, one of which is called on key press event of each text box (to validate character typed in by user is numeric) and the other function is to automatically set the focus to next text box when current text box value reaches maximum length.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Demo</title>
<script type="text/javascript" language="javascript">
function KyP(obj1)
{
var vl=String.fromCharCode(event.keyCode);
if(!IsNumber(vl))
return false;
return true;
}
function IsNumber(argVal)
{
var nmr='0123456789';
for(var i=0;i<argVal.length;i++)
{
if(nmr.indexOf(argVal.charAt(i))==-1)
return false;
}
return true;
}
function KyUp(obj1,obj2)
{

if(obj1.maxLength==obj1.value.length)
{
if(obj2==null)
{
alert('Thank you');
return;
}
obj2.focus();
}
}

</script>
</head>
<body>
<table>
<tr><td colspan="5">Please enter your land line number</td></tr>
<tr><td>Country code</td><td>-</td><td>STD</td><td>-</td><td>Line number</td></tr>
<tr><td><input type="text" id="txt1" maxlength="4" onkeypress="return KyP(this);" onkeyup="KyUp(this,document.getElementById('txt2'));"/></td><td>-</td><td><input type="text" id="txt2" maxlength="2" onkeypress="return KyP(this);" onkeyup="KyUp(this,document.getElementById('txt3'));"/></td><td>-</td><td><input type="text" id="txt3" maxlength="8" onkeypress="return KyP(this);" onkeyup="KyUp(this,null);"/></td></tr>
</table>
</body>
</html>





No comments:

Post a Comment