Thursday, November 10, 2011

WaterMark in ASP.Net TextBox Multiline TextBox TextArea using JavaScript

Basically developers use watermark textbox to give a small hint to the user to input valid or meaningfull data. We found a lot of way to watermark a TextBox using Javascript but in this article or tutorial i will explain a very simple and easy way to implement watermark in textbox / textarea / multiline TextBox. A sample output is given below:

Watermark TextBox

The main javascript method to implement watermark is:
01function WaterMarkFocus(txt, text)
02        {
03            if (txt.value == text)
04            {
05                txt.value = "";
06                txt.style.color = "black";
07            }
08        }
09 
10        function WaterMarkBlur(txt, text)
11        {
12            if (txt.value == "")
13            {
14                txt.value = text;
15                txt.style.color = "gray";
16            }
17        }
To implement the above sample output add an aspx page into your project then enter the below HTML markup:
01<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Watermark_TextBox.aspx.cs" Inherits="Watermark_TextBox" %>
02 
03<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04 
05<html xmlns="http://www.w3.org/1999/xhtml" >
06<head runat="server">
07    <title>How to Implement Watermark TextBox</title>
08 
09<script language="javascript" type="text/javascript">
10        function WaterMarkFocus(txt, text)
11        {
12            if (txt.value == text)
13            {
14                txt.value = "";
15                txt.style.color = "black";
16            }
17        }
18 
19        function WaterMarkBlur(txt, text)
20        {
21            if (txt.value == "")
22            {
23                txt.value = text;
24                txt.style.color = "gray";
25            }
26        }
27    </script>   
28 
29</head>
30<body>
31    <form id="form1" runat="server">
32    <div>
33        <asp:textbox ID="txtSearch" Text="Use ; as a separator" onfocus="WaterMarkFocus(this,'Use ; as a separator')" onblur="WaterMarkBlur(this,'Use ; as a separator')"  runat="server" ForeColor="gray" ></asp:textbox>   
34        <asp:Button runat="server" ID="cmdButton" Text="Search" />
35    </div>
36    </form>
37</body>
38</html>

No comments:

Post a Comment