Textbox watermark text effect in ASP.NET and jQuery

Having watermark effect on textbox helps user to understand what they can do in that textbox, on the top of that, it's a best place to put help text that will disappear as soon as user clicks inside the textbox. Today we are going to built such functionality and let me point out the benefit of this functionality over Ajax control toolkits textbox watermark extender is that this will detect all textboxes on the page and will extend this functionality as oppose to the extender control where you will have to attach one extender for each textbox on the page (I don't know about you but I would not want to do that).

Here is the screenshot of out end result:

Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.2.min.js"></script>

 

<style type="text/css">

.watermark

{

font-style:oblique;

font-size:small;

color:Gray;

text-transform:uppercase;

background-color:lightblue;

}

</style>

<script type="text/javascript">

$(document).ready(function () {

// function to add watermark text

function WaterMarkText(sender) {

 

if ($(sender).val() == $(sender).attr('title') || $(sender).val() == "") {

$(sender).val($(sender).attr('title')).addClass('watermark');

}

}

// function to remove watermark text

function RemoveWaterMark(sender) {

 

$(sender).removeClass('watermark').val("");

}

 

// here we are collecting all input of type text in a variable

var allInputText = $('input:text');

// each function will loop thru all the inputs one by one

$.each(allInputText, function (index, val) {

var sender = '#' + val.id;

WaterMarkText(sender);

 

$(sender).focusout(function () {

WaterMarkText(sender);

});

$(sender).focusin(function () {

RemoveWaterMark(sender);

});

});

 

});

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

 

</div>

<asp:TextBox ID="TextBox1" runat="server" ToolTip="Search here..."></asp:TextBox>

<asp:TextBox ID="TextBox2" runat="server" ToolTip="Now here..."></asp:TextBox>

<asp:TextBox ID="TextBox3" runat="server" ToolTip="and now here..."></asp:TextBox>

</form>

</body>

</html>

Tags: ,

ASP.NET | jQuery