Tuesday, June 19, 2007

Auto Fill up Leading Zero(s)

There came another requirement.
When the user didn't key in the max length in the first text box, leading zero(s) will automatically be added to fill up the space.
For example:
Telephone number: (12)-(12345678)
If the user only entered "12", it hasn't reached the max length (3) yet, then a leading zero will be added to become "012".

I'm still using the javascript here. Add the following script in the <head> block:

<script language=javascript>

function AddLeadingZero(currentField)
//Check if the value length hasn't reach its max length yet
if (currentField.value.length != currentField.maxLength)
//Add leading zero(s) in front of the value
var numToAdd = currentField.maxLength - currentField.value.length;
var value ="";
for (var i = 0; i
< numToAdd;i++)
value += "0";

currentField.value = value + currentField.value;


Copy this function in the code file:

public static void AddLeadingZeroAttribute(TextBox txt)
//Add leading zero when focus is lost
txt.Attributes.Add("OnBlur", "AddLeadingZero(this)");


"OnBlur" event will be triggered when the textbox loses the focus.
Whenever the user finished keying in values and left the textbox, the AddLeadingZero() function will be called.


  1. The solution seems pretty good... but you forget the script block... you don,t know how much I need right now that block. :(

  2. I'm really sorry, I did post the script block, but forgot to cater for the brackets <> (need to convert the <> in order to display them).

    I've modified the blog, and added the script block, hope you will come back and read this. ^_^