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>





3 comments:

الأستاذ حمام said...

how to get the list of numbers ?

Programming and Database Concepts said...

Hi,

Sorry, could you please describe in more exactly.
Do you mean
as soon as user types in number, we should populate existing phone numbers that match?
If so, then we need to implement Ajax

الأستاذ حمام said...

what i mean..

i am a blogger, there are some wedgets for email subscrptions when reader submit their emails any new activity will be sent to them right? when they write their email their will be a list of all email subscibed to your blog.. such as feedburner.com..

i would like to create similar concept, but instead of getting email list, i want readers to submit their mobile phone # and the new widgets just provide me with the list of numbers submitted, no need for sending any sms text messeges.. how to get this widget? am i clear now?