Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Applying a watermark to a textbox in a Web Application

3.39/5 (16 votes)
29 Aug 2006Ms-PL1 min read 1   1.5K  
An article on using JavaScript in ASP.NET for applying a watermark to a textbox in a Web Application.

Introduction

You may have seen some web sites displaying watermarks in text boxes. As soon as you click on a text box, the watermark disappears and you can start entering text. In this article, I will explain a small JavaScript trick that you can use to do the same in your web application. I have included a library that you can use to achieve the same functionality without having to worry about writing JavaScript code.

Sample screenshot

Background

The idea is to capitalize on the OnFocus and OnBlur events of the HTML input tag. The library sets flips between two styles for the input tag and, also, it checks if the default text has been changed or not.

Using the code

To use the code, you need to provide at least two styles for the text box. One that represents the watermarked textbox and another that represents a normal textbox. The sample project includes such a stylesheet.

To apply watermark to a textbox with id=textbox1, write the following in your page_load event handler:

VB
TextBoxWatermark.WaterMarkHelper.ApplyWaterMarkToTextBox(textBox1, _
   "Watermarktext", "WaterMarkedTextBoxStyle", "NormalTextBoxStyle")

Enhancements

You can enhance the library to intercept the submit event and remove the default text before the required field validators fire.

Update history

  • August 30, 2006: Patched the single quote bug. The library used to break down when a single quote was supplied in WatermarkText.
  • August 23, 2006: Patched the library to work with Firefox.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)