In this article I will explain how to display default Text Label in TextBox using JavaScript in ASP.Net.
The process to display default Text Label in TextBox is known as Watermarking.
 
Watermark JavaScript function
The script will be called on onblur and onfocus events of the textbox. The script simply does the following two checks
1. If the TextBox is empty and the event type is blur event it sets the watermark and changes the font color as Gray.
2. If the TextBox text matches default text and the event type is the focus it clears the textbox and sets the font color as Black.
<script type = "text/javascript">
    var defaultText = "Enter your text here";
    function WaterMark(txt, evt)
    {
        if(txt.value.length == 0 && evt.type == "blur")
        {
            txt.style.color = "gray";
            txt.value = defaultText;
        }
        if(txt.value == defaultText && evt.type == "focus")
        {
            txt.style.color = "black";
            txt.value="";
        }
    }
</script>
 
 
Implementing the Watermark JavaScript with ASP.Net TextBox
The Watermark JavaScript function can be implemented with the ASP.Net TextBox in the following two ways.
Client Side
The Watermark JavaScript function can be directly applied by attaching the onblur and onfocus event handlers and passing the reference of the TextBox and the event object.
<asp:TextBox ID="TextBox1" runat="server" Text = "Enter your text here"
    ForeColor = "Gray" onblur = "WaterMark(this, event);"
    onfocus = "WaterMark(this, event);">
</asp:TextBox>
 
Code Behind
The first solution does work, but it will make Visual Studio display Warning messages which some of you might feel annoying and hence there’s also a cleaner way of attaching the onblur and onfocus event handlers from the code behind in the Page Load event as shown below.
C#
TextBox1.Attributes.Add("onblur", "WaterMark(this, event);");
TextBox1.Attributes.Add("onfocus", "WaterMark(this, event);");  
 
VB.Net
TextBox1.Attributes.Add("onblur", "WaterMark(this, event);")
TextBox1.Attributes.Add("onfocus", "WaterMark(this, event);"
 
 
Screenshot
Watermark TextBox using JavaScript
 
 
Browser Compatibility
The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

 

* All browser logos displayed above are property of their respective owners.

 

 
 
Demo
 
 
Downloads