Wednesday, March 11, 2009

Watermark Asp.NET Textbox Using JavaScript

Noticed the watermark implemented in custom google search TextBox, like one in the right side of this page (under heading Search asp.net, C#, oracle, SQL Server related tips and solutions)? I am showing the simple and meaningful watermark implementation of a textbox in asp.net web page in this tipsticle (tips + article).

Truly saying, every time I come across a web page, I do naturally look for the searching textbox in the website. And I do usually find it in the left corner or the right upper corner of the website. Not all the search textboxes implement the watermark but they may initialize the text in the search textbox like your search text here or just search. And my enthusiasm always inspires me to click once and then just click out the textbox to see if watermark has been implemented. In my opinion, it is good to implement watermark for the sake of user-interactivity of a website. (And let me praise facebook homepage for this!)

Ok, lets start out with a search textbox in an asp.net web page.


Now we add a javascript code snippet in the page.



function WatermarkFocus(txtElem, strWatermark) {
if (txtElem.value == strWatermark) txtElem.value = '';
}
function WatermarkBlur(txtElem, strWatermark) {
if (txtElem.value == '') txtElem.value = strWatermark;
}

Now is the time to add onblur and onfocus properties to the asp.net TextBox, referencing the relevant javascript function.

string strWatermarkSearch = "Search";
txtSimpleSearch.Text = strWatermarkSearch;
txtSimpleSearch.Attributes.Add("onfocus", "WatermarkFocus(this, '" + strWatermarkSearch + "');");
txtSimpleSearch.Attributes.Add("onblur", "WatermarkBlur(this, '" + strWatermarkSearch + "');");

We can see the perfect watermark implementation with our search textbox now! Happy Programming!

Liked the post? You can share this post by submitting to dzone,digg,dotnetkicks etc. You can even leave your suggestions as the comment below.


kick it on DotNetKicks.com

2 comments:

C# said...

Nice post. I am having a question for you. In the text box if I type something and after that i click a button which takes me to next page but when i come back and type again in the text box it still remembers the value what i typed before. Do you know soem way to get rid of this issue

Unknown said...

Dear C#,
When you press back button of the browser, it displays the cached version of the page. This means the page is not served from server. You can try clearing the cache of the browser on back navigation. Thanks.

Post a Comment

Hope you liked this post. You can leave your message or you can put your valuable suggestions on this post here. Thanks for the sharing and cooperation!

Popular Posts

Recent Articles