How to Set Watermark in ASP.NET TextBox

Do you know what is Watermark in ASP.Net and how to set watermark in TextBox in ASP.Net Textbox.

Watermark

It is a pretext which shows in a textbox in a very light color. When we click on textbox it hide and when we click outside from textbox without write any text again shows the pretext. 

There is many way to do this. I am explaining with Javasacript.

<script language="javascript" type="text/javascript">

      function Focus(objname, waterMarkText) {

      obj = document.getElementById(objname);

      obj.value = "";

      if (obj.value == waterMarkText) {

           obj.value = "";

           obj.className = "WaterMarkedTextBox";

           if (obj.value == "User Name" || obj.value == "" || obj.value == null) {

                obj.style.color = "gray";

           }

        }

    }

    function Blur(objname, waterMarkText) {

       obj = document.getElementById(objname);

       if (obj.value == "") {

           obj.value = waterMarkText;

           obj.className = "WaterMarkedTextBox";

           obj.style.color = "gray";

        }

}

</script>

 
In above code two method are Focus and Blur . When you click on textbox it call Focus and when click outside it call Blur.Both methods contain two parameter :

  • Objname - TextBox Id.
  • waterMarkText - Watermark text which you want to show.

Here is a complete code :

<head id="Head1" runat="server">

    <title></title>

    <style type="text/css">

        .WaterMarkedTextBox

        {

            height: 16px;

            width: 268px;

            padding: 2px 2 2 2px;

            border: 1px solid #BEBEBE;

            background-color: #F0F8FF;

            color: gray;

            font-size: 8pt;

            text-align: center;

        }

    </style>

 

    <script language="javascript" type="text/javascript">

            function Focus(objname, waterMarkText) {

            obj = document.getElementById(objname);

            obj.value = "";

            if (obj.value == waterMarkText) {

                obj.value = "";

                obj.className = "WaterMarkedTextBox";

                if (obj.value == "User Name" || obj.value == "" || obj.value == null) {

                    obj.style.color = "gray";

                }

            }

        }

        function Blur(objname, waterMarkText) {

            obj = document.getElementById(objname);

            if (obj.value == "") {

                obj.value = waterMarkText;

                obj.className = "WaterMarkedTextBox";

                obj.style.color = "gray";

            }

        }

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:TextBox ID="txtUserId" runat="server" onfocus="Focus(this.id,'Password')" onblur="Blur(this.id,'Password')"

            Width="126px" CssClass="WaterMarkedTextBox" Text="Password"></asp:TextBox>

    </div>

    </form>

</body>

Ebook Download
View all
Learn
View all