Friday, January 9, 2009

JavaScript: Masking on Text Field

It is quite often that when we create HTML forms we need masking in fields and most of the times in text fields(Text Boxes) for some specific type of input like for DATE, PHONE NO, CURRENCY etc. Couple of server side technologies provide built in controls for most common masking but a few does not.

The following Javascript function provides you the facility to customize you text boxes with specific masking.

For Example, you may need masking for data input like : DD/MM/YYYY e.g 31/12/2008
Similarly sometimes you may want to provide masking like: 121-23-1231
and sometimes you may want to provide masking like: 12-42-1412

The following function is smart enough to handle all these requirements with a little change in the input parameter.

function mask(str,textbox,loc,delim){
var locs = loc.split(',');

for (var i = 0; i <= locs.length; i++){
for (var k = 0; k <= str.length; k++){
if (k == locs[i]){
if (str.substring(k, k+1) != delim){
str = str.substring(0,k) + delim + str.substring(k,str.length)
}
}
}
}
textbox.value = str
}

Where the parameters are for:
  1. str - the value of the current textbox control,
  2. textbox - the actual textbox object, (so that the value can be set)
  3. loc - a string of multiple locations to place the specified character,
  4. delim - the character (delimiter) that you want to use a separator.
Examples to Call this function:

Step 1:
First of all add this function in the head section.

Step 2:
You need to call this function on onKeyUp & onBlur events like:

To provide the output like(121-23-1231):

You need to call this javascript function like:
< name="Field1" value="" type="text" onkeyup="javascript:return mask(this.value,this,'3,6','-');" onblur="javascript:return mask(this.value,this,'3,6','-');" style="font-family:verdana;font-size:10pt;width:110px;" maxlength="11">



To provide the output like(21/12/2009):

You need to call this javascript function like:
< name="Field2" value="" type="text" onkeyup="javascript:return mask(this.value,this,'2,5','/');" onblur="javascript:return mask(this.value,this,'2,5','/');" style="font-family:verdana;font-size:10pt;width:110px;" maxlength="10">


To provide the output like(12,23,2312):

You need to call this javascript function like:
< name="Field3" value="" type="text" onkeyup="javascript:return mask(this.value,this,'2,5',',');" onblur="javascript:return mask(this.value,this,'2,5',',');" style="font-family:verdana;font-size:10pt;width:110px;" maxlength="10">

To provide the output like(12#32#1312):

You need to call this javascript function like:
< name="Field3" value="12#32#1312" type="text" onkeyup="javascript:return mask(this.value,this,'2,5','#');" onblur="javascript:return mask(this.value,this,'2,5','#');" style="font-family:verdana;font-size:10pt;width:110px;" maxlength="10">

You may change your mask symbol and the places accordingly using the provided parameters.

No comments: