WaterMark In ASP.NET TextBox Using JavaScript

This blog will show you, how you can display  a watermark in a textbox of ASP.NET, using JavaScript. For this, we will create a new ASP.NET Application and add a textbox control on the page. 
  1. <div>  
  2.     Username :<asp:textbox ID="txtUserName" Text="Use ; as a separator" Font-Bold="true" onfocus="WaterMarkFocus(this,'Enter your username')" onblur="WaterMarkBlur(this,'Enter your username')"  runat="server" ForeColor="gray" ></asp:textbox>      

  3. </div>  
After this, we will add JavaScript code, given below, to display the watermark. 
  1. <script type="text/javascript">  
  2.     function WaterMarkFocus(txt, text) {  
  3.         if (txt.value == text) {  
  4.             txt.value = "";  
  5.             txt.style.color = "black";  
  6.         }  
  7.     }  
  8.    
  9.     function WaterMarkBlur(txt, text) {  
  10.         if (txt.value == "") {  
  11.             txt.value = text;  
  12.             txt.style.color = "gray";  
  13.         }  
  14.     }  
  15. </script>  
This JavaScript function uses a parameter value. This value will be used as a watermark text. When a user makes a focus on textbox, watermark text will disappear and on removing the mouse, watermark text will appear.

In case the user types some text, it will remain the same.

output
Ebook Download
View all
Learn
View all