May 24, 2011

Asp.Net multiline textBox character counting to custom limit via JavaScript

Here's the code to tells that how can I limit the user to certain characters length using javascript along with asp.net Textbox control

ASPX MARKUP


<div>
    <p>
        Asp.Net TextBox Character Counting using Javascript Limit Characters to 135
    </p>
    <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" onKeyUp="CheckLimit();"></asp:TextBox><asp:RequiredFieldValidator
        ID="RequiredFieldValidator2" runat="server" ErrorMessage="*" ControlToValidate="txtMessage"
        Display="Dynamic"></asp:RequiredFieldValidator>
    <font size="1">(Maximum characters: 135)<br />
        You have
        <asp:Label ID="lblCountLimit" runat="server" Text="135" ForeColor="Red"></asp:Label>
        characters left.</font>
</div>

JAVASCRIPT CODE

function CheckLimit() {
var textField =
    document.getElementById("<%=txtMessage.ClientID %>");
var labelCount =
    document.getElementById("<%=lblCountLimit.ClientID %>");

   if (textField.value.length > 135) {
       textField.value = textField.value.substring(0, 135);
   } else {
       labelCount.innerHTML = 135 - textField.value.length;
   }
}