Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Posts Tagged ‘textbox’

Watermark TextBox using JavaScript

Posted by Viral Sarvaiya on July 11, 2009

<script type = "text/javascript">

var defaultText = "Enter your text here";

function WaterMark(txt, evt)


if(txt.value.length == 0 && evt.type == "blur")

{ = "gray";

txt.value = defaultText;


if(txt.value == defaultText && evt.type == "focus")

{ = "black";





The script will be called on onblur and onfocus events of the textbox. The script simply does the following two checks

1. If the textbox is empty and the event type is blur event it sets the watermark and changes the font color as Gray.

2. If the textbox text matches default text and the event type is the focus it clears the textbox and sets the font color as Black.

That’s all and just we now need to call it with the textbox.

<asp:TextBox ID="TextBox1" runat="server" Text = "Enter your text here"

ForeColor = "Gray" onblur = "WaterMark(this, event);"

onfocus = "WaterMark(this, event);">


As you will notice I am calling the same script on onblur and onfocus event and passing the reference of the textbox and the event object.

Visual Studio will throw warning when you call client side event in the above way. So if you do not want to get the warnings you can do in the following way from code behind.

TextBox1.Attributes.Add("onblur", "WaterMark(this, event);")

TextBox1.Attributes.Add("onfocus", "WaterMark(this, event);")


Posted in ASP.NET, Javascript | Tagged: , , , | Leave a Comment »

Text Box Characters Counter

Posted by Viral Sarvaiya on March 13, 2009

Here’s another way around for you

<script type=”text/javascript” language=”javascript”>

function validatelimit(obj, maxchar)

if( obj = this;

var remaningChar = maxchar – obj.value.length;
document.getElementById(’<%= Label1.ClientID %>’).innerHTML = remaningChar;

if( remaningChar <= 0)
obj.value = obj.value.substring(maxchar,0);
return false;

{return true;}



<asp:TextBox ID=”TextBox1″ runat=”server” TextMode=”MultiLine” onkeyup=”return validatelimit(this,500)” Height=”400px”></asp:TextBox>
<asp:Label ID=”Label1″ runat=”server” Text=”500″></asp:Label>

Posted in ASP.NET, Javascript | Tagged: , , , | Leave a Comment »

%d bloggers like this: