Hint text in ASP.NET TextBox controls

More and more often these days, you see hint text in a textbox control on a web form.  You know the kind of thing – “user name” or “password” appearing in silver text within an input control.  Well, I had to implement that functionality today and it is surprisingly easy to achieve.

The first thing you need to do is create your TextBox control on the page.  Once you’ve done that, add the following method to your codebehind file.

private void SetTextBoxHints(TextBox textBox, string defaultText)
{
textBox.Attributes.Add(“onfocus”, “clearText(this,’” + defaultText + “‘)”);
textBox.Attributes.Add(“onblur”, “resetText(this,’” + defaultText + “‘)”);
if (textBox.Text == “”)
{
textBox.Text = defaultText;
textBox.ForeColor = System.Drawing.Color.Silver;
}
else if (textBox.Text == defaultText)
{
textBox.ForeColor = System.Drawing.Color.Silver;
}
else
{
textBox.ForeColor = System.Drawing.Color.Black;

}

 Next, you’ll need to add the javascript to the page/user control to look after the dynamic changes in content/colour. 

<script type="text/javascript" language="javascript">
<!--
function clearText(ctrl,defaultText) {
if(ctrl.value == defaultText)
ctrl.value = ""
ctrl.style.color = "#000000";
}
function resetText(ctrl,defaultText) {
if(ctrl.value == "")
{
 ctrl.value = defaultText
 ctrl.style.color = "#C0C0C0";
}
}
// -->
</script>

Then, you need to call the setup method for each Textbox you want to control.

SetTextBoxHints(myControl, "the text you want to show as default...");

And that, as they say, is that. Enjoy.

This entry was posted in microsoft and tagged , , , . Bookmark the permalink.

6 Responses to Hint text in ASP.NET TextBox controls

  1. yaip says:

    Dude, where is the EmbedVideo Plugin for WLW?

  2. Jay says:

    Great!

  3. Arnaud says:

    Thanks a lot, two hours that i was searching for this !!!

  4. Karl says:

    Perfect! Just what I was looking for.

    One question though… when I postback my form and the control hasn’t had any additional text put in it, and I check the text of the textbox, it gives me the hint text. Is this normal? I can simply check that the string isn’t my hint when I process it, but just wondered if there was any other way to prevent this?

    Thanks!

  5. Marc says:

    Karl – yes it is normal – after all this technique sets the text in the the control. I guess you could do a bit of jQuery goodness to check the value on submission and reset it to blank if the value == hint text.

  6. mzukisi mndwangu says:

    This has been useful and easy to implement. and it’s so flexible as one can call it anywhere on the code.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>