Tuesday, October 23, 2012

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.