[JavaScript]Clear the content of a textbox when it gets the focus

(I truly believe that a professional Web developer cannot live without JavaScript, and I have been busy playing with JavaScript lately and I will post some common but useful JavaScript code here.)

Here is the JavaScript code:

<script language="javascript" type="text/javascript">
       function clearBox(id)
           var txt = document.getElementById(id);
           if (txt.type != "text")
             alert("Error: parameter type mismatch in clearBox function. TextBox type expected.");
               txt.value = "";

To use it in your code, just add this line of code (VB.NET) in the Page_Load event handler:

Me.TextBox1.Attribute.Add("onfocus", "clearBox('" & Me.TextBox1.ClientID.ToString() & "')")

Or for C#

this.TextBox1.Attribute.Add("onfocus", "clearBox('" + this.TextBox1.ClientID.ToString() + "')");

Some screen shots:

1. Before the text box gets the focus:

Before the text box gets the focus

2. After the text box gets the focus (without postback):

After the text box gets the focus

Leave a Reply

Notify of