Thursday, 19 April 2012

textbox watermark javascript jquery

How to add watermark to single/multiple textbox control using javascript/jquery js in Asp.net C# code:

The below sample has two approach by using jquery as well as javascript js.


Sample ASPX source code sample:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>

    <script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">

/* js on load method*/  

$(document).ready(function() {
     var watermark = 'Enter your text';
     $('#txtBox').blur(function(){
      if ($(this).val().length == 0)
        $(this).val(watermark).addClass('watermark');
     }).focus(function(){
      if ($(this).val() == watermark)
        $(this).val('').removeClass('watermark');
     }).val(watermark).addClass('watermark');
    });

/* javascript function*/   
    function watermark(inputId,text){
      var inputBox = document.getElementById(inputId);
        if (inputBox.value.length > 0){
          if (inputBox.value == text)
            inputBox.value = '';
        }
        else
          inputBox.value = text;
    }
    </script>
  
    <style type="text/css">
    #txtBox.watermark { color: #999; } /*Gray color*/
    </style>
  
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="txtBox" runat="server"></asp:TextBox>
  
    <asp:TextBox ID="txtName" runat="server" Text="Enter your name" onfocus="watermark(this.id,'Enter your name');" onblur="watermark(this.id,'Enter your name');"></asp:TextBox>
    <asp:TextBox ID="txtAddress" runat="server" Text="Enter your Address" onfocus="watermark(this.id,'Enter your Address');" onblur="watermark(this.id,'Enter your Address');"></asp:TextBox>
    </div>
    </form>
</body>
</html>

No comments:

Post a Comment