Setting The Default Button For A TextBox And Clearing A Textbox On Focus in ASP.NET
August 17th, 2007 | by programming |Today I have for you two very simple, but very useful methods to use in your ASP.NET programming.
First method is used to set a default button for the textbox. It’s the best way to make your form submit on enter nad it’s very useful if you have few forms on one page.
Without it, pressing enter will always submit first form on the webpage. Use it to manually set target form to submit.
Second method is even simpler. If you have a search box on your webpage, use it to clear it after setting the focus. It only clears the textbox if there is a cpecific value. In this example, textbox will be cleared, after getting focus, only when it’s current text is set to “Search”.
Feel free to use them in your programs.
1. Setting the default button.
public static void SetDefault(TextBox t, Button b)
{
t.AutoPostBack = false;
t.CausesValidation = false;
t.Attributes["onkeydown"] =
"javascript:if((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {document.getElementById(\"" + b.ClientID + "\").click();return false;}";
}
2. Clearing on focus, when the current value is “Search”
public static void ClearTxtMyboxScript(TextBox textBox)
{
textBox.Attributes.Add("onFocus", "ClearTextbox(this)");
StringBuilder sb = new StringBuilder();
sb.Append("<script language="\">n");
sb.Append("function ClearTextbox(theText) {n");
sb.Append("if (theText.value==\"Search\") theText.value=\"\";n");
sb.Append("}n");
sb.Append("</script>");
textBox.Page.ClientScript.RegisterClientScriptBlock(typeof(string),"ClearTextbox", sb.ToString());
}