29 May 2008

How do I clear (onclick) and restore (onblur) the default value for a text field?

Below is one example of how to clear the default text of a text field. In this example, the default text is: “Search Keywords”. If the user types text into the field, their entry will remain, allowing them the opportunity to click your “Search” button (or do whatever else is planned). However, if the user simply clicks into the field then clicks elsewhere (onblur), the default text will be returned.
<asp:TextBox ID="TextBox1" runat="server" class="searchfield" Text="Search Keywords"
onfocus="if(this.value=='Search Keywords')(this.value='');" onblur="if(this.value=='')(this.value='Search Keywords');" />
Essentially, the JavaScript reads like this: When the onclick event occurs, if the text in the text box is equal to: “Search Keywords”, set the text in the text box to nothing. When the onblur event occurs, if the text in the text box is nothing, set it to: “Search Keywords”.

For additional information on JavaScript events, please visit: http://www.irt.org/articles/js058/.

No comments: