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. function ChangeWatermark(inputId, watermarkText)
  7. {
  8. $("#" + inputId).unbind("focus");
  9. $("#" + inputId).unbind("blur");
  10. $("#" + inputId).bind("focus", function()
  11. {
  12. if (this.value == watermarkText) this.value = '';
  13. });
  14. $("#" + inputId).bind("blur", function()
  15. {
  16. if (this.value == '') this.value = watermarkText;
  17. });
  18. }
  19. function ChangeWatermarkBasedOnDropdownChange()
  20. {
  21. switch ($("#DdlSelectSearch option[value='" + $("#DdlSelectSearch").val() + "']").text())
  22. {
  23. case "Name":
  24. $("#textBoxId").val("Enter Name");
  25. ChangeWatermark('textBoxId', 'Enter Name');
  26. break;
  27. case "Zip":
  28. $("#textBoxId").val("Enter Zip");
  29. ChangeWatermark('textBoxId', 'Enter Zip');
  30. break;
  31. case "City":
  32. $("#textBoxId").val("Enter City");
  33. ChangeWatermark('textBoxId', 'Enter City');
  34. break;
  35. case "MC Id":
  36. $("#textBoxId").val("Enter MC Id");
  37. ChangeWatermark('textBoxId', 'Enter MC Id');
  38. break;
  39. default:
  40. }
  41. }
    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