Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 925
  • Last Modified:

Auto Format Form Entry?

I have a question- I have seen it done with some fancier websites using flash- but I don't have that kind of budget.

I have a form that asks for phone number, social security number, etc and I would like to be able to have the user enter numbers and have the form format them as needed:

for example: user enters 9015551212 in the phone number slot and while they type this in, (901) 555-1212 is displayed in realtime. and the same thing for SSN: 898123245 would display as 898-12-3245.

I have looked for some javascript for this function, and found one for telephone numbers, but the code is so non-descriptive.  I want to know more on how the process works.

I think this is a difficult issue, so I am offering 500 points for help regarding this task.

thanks!!!
0
jhines2000
Asked:
jhines2000
  • 10
  • 9
  • 5
  • +2
1 Solution
 
COBOLdinosaurCommented:
Okay here is one for phone numbers.  Let me know what you need to know about it, and then we can do the SS number and when we are finished you should understand how to do it for other formattables as well.

Cd&


<html>
<head>
   <title> input phone number </title>
<style>
   body {color:darkviolet;background-color:lightseagreen}
   h1 {background-color:oldlace;color:darkkhaki;text-align:center}
   table {background-color:bisque;border:5px double azure}
   input {border:0px solid white;background-color:lightyellow;
          color:peru}
   .dumbcls{color:firebrick;
            border-left:2px inset beige;border-top:2px inset beige;
            border-right:2px inset deepskyblue;border-bottom:2px inset deepskyblue;
            background-color:lightyellow}
   button {color:lightslategray;background-color:peachpuff}
</style>
<script language="JavaScript">
<!--
   var excluded =  new Array(0,8,9,16,17,18,37,38,39,40,46);
   function autoTab(fld,len,e)
   {
      var keyCode = e.keyCode;
      if(fld.value.length >= len && !testCode(keyCode))
      {
         fld.value = fld.value.slice(0, len);
         fld.form[(getIndex(fld)+1) % fld.form.length].focus();
      }
      return true;
   }
   function testCode(Kcode)
   {
      var found = false;
      var i = 0;
      while(!found && i < excluded.length)
      if(excluded[i] == Kcode)
         found = true;
      else
         i++;
      return found;
   }
   function getIndex(input)
   {
      var i = -1;
      var j = 0;
      var found = false;
      while (j < input.form.length && i == -1)
      if (input.form[j] == input)
         i = j;
      else
         j++;
      return i;
   }
   function validatePH()
   {
      var x=document.phoneNumber;
      if ((isNaN(x.PHarea.value)) || (isNaN(x.PHexch.value)) || (isNaN(x.PHnumb.value)))
         alert('Not a valid phone number');
      else
         if ((x.PHarea.value.length<3) || (x.PHexch.value.length<3) || (x.PHnumb.value.length<4))
            alert('number of digits is not correct')
         else
            x.PHstring.value='('+x.PHarea.value+')'+x.PHexch.value+'-'+x.PHnumb.value;
   }
// -->
</script>
</head>
<BODY>
<h1> Accept and Validate a Phone Number</h1>
<p> This accepts a North American phone number into what appears to be
    a single pre-edited field (actually three heavily styled fields). It
    does rudimentary validation when the validate button is clicked.
</p>
<br>
<form name="phoneNumber">
<table align="center">
<tr>
<td>Phone Number : <br>
<div class="dumbcls">
 (
<input type="text" name="PHarea"
       onKeyUp="return autoTab(this,3,event);" size="3" maxlength="3">)
<input type="text" name="PHexch"
       onKeyUp="return autoTab(this,3,event);" size="3" maxlength="3">-
<input type="text" name="PHnumb"
       onKeyUp="return autoTab(this,4,event);" size="4" maxlength="4">
</div>
</td>
</tr>
<tr>
<td align="center">
<br>
<button onClick="validatePH()">Validate</button>
</td>
</tr>
<tr>
<td align="center">
<input type="text" name="PHstring" size="13" maxlength="13"
       class="dumbcls" readonly><br>
<button onClick="document.phoneNumber.reset()">Reset</button>
</td>
</tr>
</table>
</form>
</body>
</html>
0
 
jhines2000Author Commented:
Hi COBOLDinosaur,

I found this script, that works, but I have no idea why :)

I want to hack it to create on that works with SSN.


*_----------------------------------

<HEAD>

<SCRIPT LANGUAGE="JavaScript">

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Original:  Roman Feldblum (web.developer@programmer.net) -->

<!-- Begin
var n;
var p;
var p1;
function ValidatePhone(){
p=p1.value
if(p.length==3){
     //d10=p.indexOf('(')
     pp=p;
     d4=p.indexOf('(')
     d5=p.indexOf(')')
     if(d4==-1){
          pp="("+pp;
     }
     if(d5==-1){
          pp=pp+")";
     }
     //pp="("+pp+")";
     document.frmPhone.txtphone.value="";
     document.frmPhone.txtphone.value=pp;
}
if(p.length>3){
     d1=p.indexOf('(')
     d2=p.indexOf(')')
     if (d2==-1){
          l30=p.length;
          p30=p.substring(0,4);
          //alert(p30);
          p30=p30+")"
          p31=p.substring(4,l30);
          pp=p30+p31;
          //alert(p31);
          document.frmPhone.txtphone.value="";
          document.frmPhone.txtphone.value=pp;
     }
     }
if(p.length>5){
     p11=p.substring(d1+1,d2);
     if(p11.length>3){
     p12=p11;
     l12=p12.length;
     l15=p.length
     //l12=l12-3
     p13=p11.substring(0,3);
     p14=p11.substring(3,l12);
     p15=p.substring(d2+1,l15);
     document.frmPhone.txtphone.value="";
     pp="("+p13+")"+p14+p15;
     document.frmPhone.txtphone.value=pp;
     //obj1.value="";
     //obj1.value=pp;
     }
     l16=p.length;
     p16=p.substring(d2+1,l16);
     l17=p16.length;
     if(l17>3&&p16.indexOf('-')==-1){
          p17=p.substring(d2+1,d2+4);
          p18=p.substring(d2+4,l16);
          p19=p.substring(0,d2+1);
          //alert(p19);
     pp=p19+p17+"-"+p18;
     document.frmPhone.txtphone.value="";
     document.frmPhone.txtphone.value=pp;
     //obj1.value="";
     //obj1.value=pp;
     }
}
//}
setTimeout(ValidatePhone,100)
}
function getIt(m){
n=m.name;
//p1=document.forms[0].elements[n]
p1=m
ValidatePhone()
}
function testphone(obj1){
p=obj1.value
//alert(p)
p=p.replace("(","")
p=p.replace(")","")
p=p.replace("-","")
p=p.replace("-","")
//alert(isNaN(p))
if (isNaN(p)==true){
alert("Check phone");
return false;
}
}
//  End -->
</script>

</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document  -->

<BODY>

<div align="center">
<form name=frmPhone>
<font size="4" color="#0000FF"><b>Enter Telephone Number</b></font><br>
(To refresh, hold down shift and press the browser refresh button)<br>
<input type=text name=txtphone maxlength="13" onclick="javascript:getIt(this)" >
</form>
</div>


<p><center>
<font face="arial, helvetica" size"-2">Free JavaScripts provided<br>
by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>


*_---------------------------------------


That's it.

Your code looks nice, but actually uses a few fields, this one is just one field.

0
 
COBOLdinosaurCommented:
That code does not look complete.  It is extrememly inefficient, and quite incomprehensible.  

I guess if I played with it I could get it cleanup and might even get it to do other stuff, but I don't have the time.  You should try emailing the author.  They might be able to help you out with it.

Cd&
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
lil_puffballCommented:
Well, here is a simple phone # script:

<script>
function change(input) {
var nums="0123456789"
var valid=true;

for(i=0;i<=9;i++) {
if(nums.indexOf(input.charAt(i))==-1)
{valid=false;}}

if(input.length!=10)
{alert('Invalid Number!');}

else if(valid==false)
{alert('Invalid Number!');}

else {
var first=input.substring(0,3);
var second=input.substring(3,6);
var third=input.substring(6,10);
var phone_num='(' +first+ ')-' +second+ '-' +third;
document.forms[0].elements[0].value=phone_num;
}

}
</script>

<form>
<input type="text">
<input type="button" onClick="change(this.form.elements[0].value)" value="Change">
</form>


It's not perfect yet, but it's an example...so is this the type of thing you're looking for?

Also...I don't know much about SSN so you'll have to supply the rules for me...:)
0
 
lil_puffballCommented:
Now I've improved the script a bit so if the user enters brackets or dashes, it'll still work:

<script>
function change(input) {
var nums="0123456789()-";
var other="()-";
var valid=true;

for(i=0;i<=input.length-1;i++) {
if(nums.indexOf(input.charAt(i))==-1)
{valid=false;}
if(other.indexOf(input.charAt(i))!=-1)
{input=input.split(input.charAt(i)).join("");}
}

if(input.length<10)
{alert('Invalid Number!');}

else if(valid==false)
{alert('Invalid Number!');}


else {
var first=input.substring(0,3);
var second=input.substring(3,6);
var third=input.substring(6,10);
var phone_num='(' +first+ ')-' +second+ '-' +third;
document.forms[0].elements[0].value=phone_num;
}

}
</script>

<form>
<input type="text">
<input type="button" onClick="change(this.form.elements[0].value)" value="Change">
</form>
0
 
yyilmazCommented:
Jhines, here's a complete solution... I used this a while ago and it works very well - it strips any unwanted characters too... as soon as the user moves off the text box.

If you want to add formatting of any other fields, it should be very straight forward: just duplicate a function (e.g. formatAsTelephone()) and change the line that sets the value for sOut. It is as efficient as you can probably get... :-)



<html>
<title></title>
<head>
<SCRIPT LANGUAGE="JavaScript">
<!--
function removeStringList(StringField, charList, bStrip) {
    // USAGE: removeStringList('ABC123a.bc','1234567890',true); will result = 'ABCabc'
     // USAGE: removeStringList('ABC123a.bc', '0123456789.', false); will result = '123.'
    var sOutString = '';
    for (iPos=0;iPos < StringField.value.length;iPos++) {
        if (bStrip)    {
            if (charList.indexOf(StringField.value.charAt(iPos))==-1)
                sOutString = sOutString + StringField.value.charAt(iPos);
        } else {
            if (charList.indexOf(StringField.value.charAt(iPos))>-1)
                sOutString = sOutString + StringField.value.charAt(iPos);
        }
    }
    StringField.value = sOutString;
}

function formatAsTelephone(field) {
    removeStringList(field, "0123456789", false);
    var sTmp = parseFloat(field.value)
    if (sTmp+"" == "undefined" || sTmp+"" == "null" || isNaN(sTmp)) {
          alert("This does not appear to be a valid number. Please try again.");
          field.focus();
     } else {
         sOut = "";
         sTmp += "";
          if (sTmp.length != 10) {
               alert("Please enter telephone number formatted as (000)555-1234");
               field.focus();
          } else {
               sOut = "(" + sTmp.substring(0,3) + ")" + sTmp.substring(3,6) + "-" + sTmp.substring(6,10);
               field.value = sOut;
          }
     }
}

function formatAsSSN(field) {
    removeStringList(field, "0123456789", false);
    var sTmp = parseFloat(field.value)
    if (sTmp+"" == "undefined" || sTmp+"" == "null" || isNaN(sTmp)) {
          alert("This does not appear to be a valid number. Please try again.");
          field.focus();
     } else {
         sOut = "";
         sTmp += "";
          if (sTmp.length != 9) {
               alert("Please enter SSN formatted as 000-55-1234");
               field.focus();
          } else {
               sOut = sTmp.substring(0,3) + "-" + sTmp.substring(3,5) + "-" + sTmp.substring(5,9);
               field.value = sOut;
          }
     }
}
//  End -->
</script>
</head>

<body>
<form name=commaform>
enter a number and click outside the textbox:<br>
TEL: <input type=text name=tel size=15 value="" onBlur="formatAsTelephone(this)"><br>
SSN: <input type=text name=ssn size=15 value="" onBlur="formatAsSSN(this)">
</form>
</body>

0
 
jhines2000Author Commented:
Hey guys,

if you read my second post, that code works, however, I just want to disect it and make another function for SSN.

Wilmaz, your SSN works great, however, the phone loops if the user enters the wrong number in.

thanks!
0
 
jaysolomonCommented:
Cd&,

If noone appreciates the Phone Script that you give, i will have to say thats pretty impressive. Thanks, i throwed that one in my toolbox.

jAy
0
 
COBOLdinosaurCommented:
If I get some time a little later today I will post some script that gives the really time look of the other one with one field and common function for both phone and SSN; something more efficient and maintainable.

Cd&
0
 
jhines2000Author Commented:
thanks Cd&!
0
 
jhines2000Author Commented:
Hey guys,

I have been hacking away at this, here is what I have so far- it's close- the phone doesn't display the ( ) yet, but it is working thus far.  



<HTML>
<HEAD>

<SCRIPT LANGUAGE=javascript>
<!--
function formatSSN(objFormField){
   intFieldLength = objFormField.value.length;
   if(intFieldLength==3 || intFieldLength == 6){
        objFormField.value = objFormField.value + "-";
             return false;
   }
}
//-->
</SCRIPT>

<SCRIPT LANGUAGE=javascript>
<!--
function formatPHONE(objFormField){
   intFieldLength = objFormField.value.length;
   if(intFieldLength==3 || intFieldLength == 7){
             objFormField.value = objFormField.value + "-";
                  return false;
        }
}
//-->
</SCRIPT>



</HEAD>
<BODY>
<FORM name=form1>
SSN:<INPUT type="text" name=text1 onKeyPress="javascript:formatSSN(this)" maxlength="11">
Phone:<INPUT type="text" name=text2 onKeyPress="javascript:formatPHONE(this)" maxlength="12">
</FORM>

</BODY>
</HTML>
0
 
jaysolomonCommented:
try this for the Phone Number


<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<SCRIPT LANGUAGE="JavaScript">
//Begin Phone Num Format

<!-- Begin
var n;
var p;
var p1;
function ValidatePhone(){
p=p1.value
if(p.length==3){
     //d10=p.indexOf('(')
     pp=p;
     d4=p.indexOf('(')
     d5=p.indexOf(')')
     if(d4==-1){
          pp="("+pp;
     }
     if(d5==-1){
          pp=pp+")";
     }
     //pp="("+pp+")";
     document.form1.Phone.value="";
     document.form1.Phone.value=pp;
}
if(p.length>3){
     d1=p.indexOf('(')
     d2=p.indexOf(')')
     if (d2==-1){
          l30=p.length;
          p30=p.substring(0,4);
          //alert(p30);
          p30=p30+")"
          p31=p.substring(4,l30);
          pp=p30+p31;
          //alert(p31);
          document.form1.Phone.value="";
          document.form1.Phone.value=pp;
     }
     }
if(p.length>5){
     p11=p.substring(d1+1,d2);
     if(p11.length>3){
     p12=p11;
     l12=p12.length;
     l15=p.length
     //l12=l12-3
     p13=p11.substring(0,3);
     p14=p11.substring(3,l12);
     p15=p.substring(d2+1,l15);
     document.form1.Phone.value="";
     pp="("+p13+")"+p14+p15;
     document.form1.Phone.value=pp;
     //obj1.value="";
     //obj1.value=pp;
     }
     l16=p.length;
     p16=p.substring(d2+1,l16);
     l17=p16.length;
     if(l17>3&&p16.indexOf('-')==-1){
          p17=p.substring(d2+1,d2+4);
          p18=p.substring(d2+4,l16);
          p19=p.substring(0,d2+1);
          //alert(p19);
     pp=p19+p17+"-"+p18;
     document.form1.Phone.value="";
     document.form1.Phone.value=pp;
     //obj1.value="";
     //obj1.value=pp;
     }
}
//}
setTimeout(ValidatePhone,100)
}
function getIt(m){
n=m.name;
//p1=document.forms[0].elements[n]
p1=m
ValidatePhone()
}
function testphone(obj1){
p=obj1.value
//alert(p)
p=p.replace("(","")
p=p.replace(")","")
p=p.replace("-","")
p=p.replace("-","")
//alert(isNaN(p))
if (isNaN(p)==true){
alert("Phone Field Invalid");
return false;
}
}
//  End -->
</script>

</head>

<body>
<form name="form1" method="post" action="">
  <input type="text" name="Phone" onClick="getIt(this)" maxlength="13" size="14">
</form>
</body>
</html>
0
 
jhines2000Author Commented:
Hey, I worked it out- however, I would like to have some help on rejecting BAD input-

I only want people to enter numbers :)  and block other characters from being entered.

Here is my modified javascript/html

<HTML>
<HEAD>

<SCRIPT LANGUAGE=javascript>
<!--
function formatSocial(objFormField){
   intFieldLength = objFormField.value.length;
   if(intFieldLength==3 || intFieldLength == 6){
        objFormField.value = objFormField.value + "-";
             return false;
   }
}
//-->

<SCRIPT LANGUAGE=javascript>
<!--
function formatPhone(objFormField){
   intFieldLength = objFormField.value.length;
   if(intFieldLength == 3){
             objFormField.value = "(" + objFormField.value + ") ";
                 return false;
            }
     if(intFieldLength >= 9 && intFieldLength <= 10){
          objFormField.value = objFormField.value + "-";
               return false;
          }
}
//-->
</SCRIPT>



</HEAD>
<BODY>
<FORM name=form1>
SSN:<INPUT type="text" name=text1 onKeyPress="javascript:formatSocial(this)" maxlength="11">
PhoneGood:<input type ="text" name=test3 onKeyPress="javascript:formatPhone(this)" maxlength="14">
</FORM>

</BODY>
</HTML>
0
 
jaysolomonCommented:
To allow only numbers add this

<SCRIPT LANGUAGE="JavaScript">
//Let Only Numbers in
function checkIt(evt) {
     evt = (evt) ? evt : window.event
     var charCode = (evt.which) ? evt.which : evt.keyCode
     if (charCode > 31 && (charCode < 48 || charCode > 57)) {
          status = "This field accepts numbers only."
          return false
     }
     status = ""
     return true
}
</SCRIPT>

And put this on the field that you only want numbers
<input type="text" name="SSN" size="9" maxlength="9" onKeyPress="return checkIt(event)">
0
 
jaysolomonCommented:
Also on your code you submitted that you said work, if i copy/paste it i get an error, and this is why

<SCRIPT LANGUAGE=javascript>
<!--
function formatSocial(objFormField){
  intFieldLength = objFormField.value.length;
  if(intFieldLength==3 || intFieldLength == 6){
       objFormField.value = objFormField.value + "-";
            return false;
  }
}
//-->
/*YOU DO NOT NEED THIS SCRIPT LANGAUGE HERE*/
//<SCRIPT LANGUAGE=javascript>
<!--
function formatPhone(objFormField){
  intFieldLength = objFormField.value.length;
  if(intFieldLength == 3){
            objFormField.value = "(" + objFormField.value + ") ";
                return false;
           }
    if(intFieldLength >= 9 && intFieldLength <= 10){
         objFormField.value = objFormField.value + "-";
              return false;
         }
}
//-->
</SCRIPT>
0
 
jaysolomonCommented:
looks like it works like a charm tho
0
 
jhines2000Author Commented:
Yes, and thanks for the Numeric validation too!

500points!
0
 
jaysolomonCommented:
i tested all of yours in NS7 and IE6 it all works like a charm
0
 
jaysolomonCommented:
if you don't mind i will add your script as i did Cd& script, into my <toolbox> for referance in the future
0
 
jhines2000Author Commented:
awesome, i like sharing code.  feel free to use anything posted here
0
 
jaysolomonCommented:
Thanks

You can split the points, with whoever you desire, if you need to
0
 
jhines2000Author Commented:
you got them
0
 
COBOLdinosaurCommented:
Good job Jay!  :^) Sorry I couldn't be around to help... been fighting fires all day.

Cd&
0
 
jaysolomonCommented:
lol Cd&

I have posted in CS to get them to split them with you, because you were the first to respond and yours was Excellent.

CS Link

http://www.experts-exchange.com/Community_Support/Q_20556444.html

I feel that it is only fair
jAy
0
 
jhines2000Author Commented:
Cd&, I am going to post a new question for ya to grab some points ;)
0
 
jaysolomonCommented:
jhines

Wait til i get a response from Community Support.

jAy
0
 
COBOLdinosaurCommented:
Jay,

You earned the points.  Now just sit back and enjoy the Good Answer! email.

Cd&
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 10
  • 9
  • 5
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now