This article, will explain how watermark textbox using JavaScript. It is very useful and uses less resourcescompared to AJAX. Below is the short JavaScriptthat helps doing the watermark. Code: <script type = "text/javascript"> var defaultText = "Enter your text here"; function waterMarkText(txt, evt) { if(txt.value.length == 0 && evt.type == "blur") { txt.style.color = "red"; txt.value = defaultText; } if(txt.value == defaultText && evt.type == "focus") { txt.style.color = "green"; txt.value=""; } } </script> The script will be called on onblur and onfocus events of the textbox. The script simply does the following two checks 1. If the textbox is empty and the event type is blur event it sets the watermark and changes the font color as Gray. 2. If the textbox text matches default text and the event type is the focus it clears the textbox and sets the font color as Black. Now we just call it withthe textbox. <asp:TextBox ID="TxtWaterMark" runat="server" Text= "Enter your text here" ForeColor = "Gray" onblur = "waterMarkText(this, event);" onfocus = "waterMarkText(this, event);"> </asp:TextBox> Now write the following code in to the code behind. C# TxtWaterMark.Attributes.Add("onblur", "waterMarkText(this,event);"); TxtWaterMark.Attributes.Add("onfocus", "waterMarkText(this,event);"); Watermark Demo: Watermark TextBox |
0 comments
Post a Comment