如何将水印添加到动态创建的文本框?
问题描述:
我有一个网页,我得到了一个动态添加的文本框的总数。我添加了一个HTML表格,我添加了行和单元格来放置文本框。如何将水印添加到动态创建的文本框?
我不想为每个文本框添加标签控件,但希望在每个文本框内放置水印文本,这些文本框是作为文本框的数组动态创建的。
请帮我实现这一点。任何代码都会好得多!
下面的代码是我写的,它只在HTML表格控件中创建了文本框。
//Add row to table
tRow = new TableRow();
tblBokingDet.Rows.Add(tRow);
//Add cell to row
tCell = new TableCell();
tRow.Cells.Add(tCell);
//Add a literal text as control
AddTextBox = new TextBox();
AddTextBox.ID = "txtName" + i;
tCell.Controls.Add(AddTextBox);
答
尝试:
AddTextBox = new TextBox();
AddTextBox.ID = "txtName" + i;
tCell.Controls.Add(AddTextBox); // add to the cell
AddTextBox.Attributes.Add("class", "hintTextbox");
AddTextBox.Attributes.Add("onfocus", "if (this.value=='Name') this.value = '';this.style.color = '#000';");
AddTextBox.Attributes.Add("onblur", "if (this.value=='') {this.value = 'Name';this.style.color ='#888';}");
添加CSS:
INPUT.hintTextbox { color: #888; }
INPUT.hintTextboxActive { color: #000; }
在这里看到样品小提琴:http://jsfiddle.net/F5R6Z/3/
答
我不知道是否有通过Ajax toolkit要连接东西的方式来动态创建在运行文本框,但这样做的一个“开放”的方法是使用JavaScript水印附加到每个你的文本框。 (我说“开放”是因为它通常将您的UI功能与您用于可移植性/可重用性的任何后端框架分开的良好实践)。
你钩住的onfocus(),并且每个文本框的的onblur()事件。当然,你需要创建一个通用的js函数来遍历每个文本框并连接它们的事件。
(单文本框)样品:
<input id="MyTextBox" type="text" value="Search" />
<script>
var MyTextBox = document.getElementById("MyTextBox");
MyTextBox.addEventListener("focus", function(){
if (this.value=='Search') this.value = '';
}, false);
MyTextBox.addEventListener("blur", function(){
if (this.value=='') this.value = 'Search';
}, false);
</script>
+0
@ ajax81 ...感谢您的帮助!将在我未来的参考中使用你的代码。 – codebug
任何代码都要好得多?? ...什么哈你试过.... –
花了我10秒钟找到这个:http://www.ozzu.com/javascript-tutorials/tutorial-watermark-text-boxes-html-javascript-jquery-t106384.html。我使用[此搜索](https://www.google.com/search?q=text+boxes+with+watermark)。 –
你需要JavaScript至少让它更容易 – Anujith