How to Set and Change Watermark at Runtime Using JavaScript

Introduction

 
I encountered the problem in my project of how to set and change a watermark during runtime in a single "text box" on the change event of a dropdown. I found various solutions on the internet but then I developed the following solution.
 
JavaScript code
  1. $(document).ready(function()    
  2. {    
  3.     $("#textBoxId").val("Enter Name");    
  4.     ChangeWatermark('textBoxId''Enter Name');    
  5. });    
  6.     
  7. function ChangeWatermark(inputId, watermarkText)    
  8. {    
  9.     $("#" + inputId).unbind("focus");    
  10.     $("#" + inputId).unbind("blur");    
  11.     $("#" + inputId).bind("focus"function()    
  12.     {    
  13.         if (this.value == watermarkText) this.value = '';    
  14.     });    
  15.     $("#" + inputId).bind("blur"function()    
  16.     {    
  17.         if (this.value == ''this.value = watermarkText;    
  18.     });    
  19. }    
  20.     
  21. function ChangeWatermarkBasedOnDropdownChange()    
  22. {    
  23.     switch ($("#DdlSelectSearch option[value='" + $("#DdlSelectSearch").val() + "']").text())    
  24.     {    
  25.         case "Name":    
  26.             $("#textBoxId").val("Enter Name");    
  27.             ChangeWatermark('textBoxId''Enter Name');    
  28.             break;    
  29.         case "Zip":    
  30.             $("#textBoxId").val("Enter Zip");    
  31.             ChangeWatermark('textBoxId''Enter Zip');    
  32.             break;    
  33.         case "City":    
  34.             $("#textBoxId").val("Enter City");    
  35.             ChangeWatermark('textBoxId''Enter City');    
  36.             break;    
  37.         case "MC Id":    
  38.             $("#textBoxId").val("Enter MC Id");    
  39.             ChangeWatermark('textBoxId''Enter MC Id');    
  40.             break;    
  41.         default:    
  42.     }    
  43. }   
    HTML Code
    1. <div class="row"> <span style="width: 50px;" class="normalGray">By:</span>    
    2.         <asp:DropDownList ID="DdlSelectSearch" runat="server" Style="width: 63px; : 12px;" onchange="ChangeWatermarkBasedOnDropdownChange(); return false" CssClass="textBox floatLeft" ClientIDMode="Static" TabIndex="101">    
    3.             <asp:ListItem Value="ZipCode">Zip</asp:ListItem>    
    4.             <asp:ListItem Value="City">City</asp:ListItem>    
    5.             <asp:ListItem Value="Name" selected="selected">Name</asp:ListItem>    
    6.             <asp:ListItem Value="Id">MC Id</asp:ListItem>    
    7.         </asp:DropDownList>    
    8.         <input type="text" name="zip1" id="textBoxId" runat="server" maxlength="50" style="width: 93px;" class="textBox floatLeft marginLr5" clientidmode="Static" tabindex="102" />     
    9.      </div>    
    jquery1.gif
     
    jquery2.gif


    Similar Articles