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.
Dude, where is the EmbedVideo Plugin for WLW?
Great!
Thanks a lot, two hours that i was searching for this !!!
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!
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.