I think this will be a better answer...
Header code:
<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 code:
<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>
It is important to set the TextBox
and Label
control's property as ClientIDMode="Static"
otherwise the control name will not be found on the javascript.
CS code:
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
}
That's it for a SingleLine
TextBox.
Now for a MultiLine
TextBox
you need to add this on your Page_Load()
so the maxLength
takes the TextBox1.MaxLength
value.:
this.TextBox1.Attributes.Add("maxLength", TextBox1.MaxLength.ToString());
Also the MaxLength
property of the TextBox
doesn't work when is on Multiline
mode so you need to add on your javascript getCountDown()
function the following lines:
// 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);
}
add them right after the var textField = document.getElementById("<%#TextBox1.ClientID %>");
line. This is to prevent the user from entering more characters than the MaxLength
value.
Pablo