Wednesday, November 19, 2008

ASP.Net Textbox watermark

I don't like to do javascript! Asked myself several times over the past years why my javascript has been so poor even it has several syntax semblance to C# and other languages with same cancer of the semi-colons ;).

What I have been able to identify a reason for dislike is the poor IDE support for javascript. Visual Studio brought quite a bit of cool supports and features but not enough for an aging brain like mine to pick up. However, rising to the challenge and had to do a textbox watermark. 

I had done this before with a sample from Stan (a friend - Great Chap) but can't seem to find the source anymore nor Stan himself and also done this with ASP.Net Ajax but the client do not want Ajax feature, nor is ready to pay more for that so I had to revert to my plain-old javascript in ASP.Net and this is what I came up with.


App_Code
public static void WatermarkHelper(TextBox textBox, bool isPostBack, string defaultText)
    {
        textBox.Attributes.Add("onfocus", isPostBack ? "" : "WatermarkFocus(this, '" + defaultText + "');");
        textBox.Attributes.Add("onblur", isPostBack ? "" : "WatermarkBlur(this, '" + defaultText + "');");

        textBox.Attributes.Add("class", isPostBack ? "normal" : "watermark");
        textBox.Text = defaultText;
    }

Page_Load
Util.WatermarkHelper(plsperacreText, IsPostBack, "Enter Code");

Javascript
function WatermarkFocus(element, defaultText) {

            if (element.value == defaultText) {
                element.className = "normal";
                element.value = "";
            }
        }

        function WatermarkBlur(element, defaultText) {
           

            if (element.value == defaultText || element.value.length == 0) {
                element.className = "watermark";
                element.value = defaultText;
            }
            else
                element.className = "normal";
        }


CSS
.watermark
{  
/* sure u can add a lot more */
   color: DarkGray;
}

.normal
{
}


And that does it

No comments: