我在asp.net中生成动态文本框并在其上设置默认文本。现在,我想在第一次聚焦时清除文本框,但如果用户没有输入任何内容,请再次显示默认文本。
protected void btnAdd_Click(object sender, EventArgs e)
{
TextBox textName;
textName = new TextBox();
textName.Text = "mail";
TextBox textName2;
textName2 = new TextBox();
textName2.Text = "tel";
string divContect = ControlRenderer(divTextBox);
divTextBox.InnerHtml = divContect + ControlRenderer(textName) + "  " + ControlRenderer(textName2) + "<br/><br/>";
}
public string ControlRenderer(Control control)
{
StringWriter writer = new StringWriter();
control.RenderControl(new HtmlTextWriter(writer));
return writer.ToString();
}
答案 0 :(得分:0)
private void OnTestTextBoxGotFocus(object sender, RoutedEventArgs e)
{
if (testTextBox.Text.Equals("Type here...", StringComparison.OrdinalIgnoreCase))
{
testTextBox.Text = string.Empty;
}
}
private void OnTestTextBoxLostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(testTextBox.Text))
{
testTextBox.Text = "Type here...";
}
}
答案 1 :(得分:0)
您可以将Javascript与onblur和onfocus事件一起使用。
希望这会对你有所帮助。
请试试这个:
protected void Button1_Click(object sender, EventArgs e)
{
TextBox textName;
textName = new TextBox();
textName.ID = "textName";
textName.Text = "mail";
textName.ForeColor = System.Drawing.Color.Gray;
SetPromptText(textName);
TextBox textName2;
textName2 = new TextBox();
textName2.ID = "textName2";
textName2.Text = "tel";
textName2.ForeColor = System.Drawing.Color.Gray;
SetPromptText(textName2);
string divContect = ControlRenderer(divTextBox);
divTextBox.InnerHtml = divContect + ControlRenderer(textName) + "  " + ControlRenderer(textName2);
}
public string ControlRenderer(Control control)
{
StringWriter writer = new StringWriter();
control.RenderControl(new HtmlTextWriter(writer));
return writer.ToString();
}
private void SetPromptText(TextBox textBox)
{
string onFocusAction = "if (this.value == \"{0}\") {{ this.value = \"\"; this.style.color = \"black\"; }} ";
string onBlurAction = " if (this.value == \"\") {{ this.value = \"{0}\"; this.style.color = \"gray\"; }} else this.style.color = \"black\";";
onBlurAction = string.Format(onBlurAction, textBox.Text);
onFocusAction = string.Format(onFocusAction, textBox.Text);
textBox.Attributes["onblur"] = onBlurAction;
textBox.Attributes["onfocus"] = onFocusAction;
}