我认为这将是一个更好的答案...
标题代码:
<script language="javascript" type="text/javascript">
function getCountDown()
{
//Get the Textbox control
var textField = document.getElementById("<%#TextBox1.ClientID %>");
//Do the math of chars left and pass the value to the label
document.getElementById('<%#Label1.ClientID %>').innerHTML = textField.maxLength - textField.value.length;
return false;
}
</script>
ASP 代码:
<asp:TextBox ID="TextBox1" runat="server" MaxLength="729" Height="80px"
Width="591px" onkeyup="getCountDown();" ClientIDMode="Static"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="" ClientIDMode="Static"></asp:Label>
将TextBox和Label控件的属性设置为ClientIDMode="Static"很重要,否则在javascript上将找不到控件名称。
CS 代码:
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
}
SingleLine TextBox 就是这样。
现在,对于 MultiLine TextBox,您需要将其添加到您的 Page_Load(),以便 maxLength 采用 TextBox1.MaxLength 值。:
this.TextBox1.Attributes.Add("maxLength", TextBox1.MaxLength.ToString());
此外,TextBox 的 MaxLength 属性在 Multiline 模式下也不起作用,因此您需要在 javascript getCountDown() 函数中添加以下行:
// Check if user is entering more than the limit of characters
if (textField.value.length >= textField.maxLength) {
// Cut extra text
document.getElementById("<%#TextBox1.ClientID %>").innerHTML = textField.value.substring(0, textField.maxLength);
}
在var textField = document.getElementById("<%#TextBox1.ClientID %>"); 行之后添加它们。这是为了防止用户输入比MaxLength 值更多的字符。
巴勃罗