Tuesday, February 7, 2012

Create Watermark TextBox using JavaScript


JavaScript code:


<script type = "text/javascript">
          var defaultText = "Search Pathfinder Trainers";
           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 = "gray";
                txt.value = "";
            }
        }
</script>


HTML code:


<asp:TextBox ID="txtsearch" runat="server" Width="320px" Text = "Search Pathfinder Trainers" CssClass="rcbInput" onblur = "WaterMark(this, event);"
                                           onfocus = "WaterMark(this, event);">
 </asp:TextBox> 


C# code:


          if (!Page.IsPostBack)
           {
                txtsearch.Attributes.Add("onblur", "WaterMark(this, event);");
                txtsearch.Attributes.Add("onfocus", "WaterMark(this, event);");
          }

No comments: