Character Count Validation using Javascript

This code allows you to enter only maximum characters.


<body>
    <form id="form1" runat="server">
    <div>
     <asp:TextBox ID="CharacterCountTextBox" TextMode="multiLine" MaxLength="100"
       runat="server"onkeyup="javascript:CharCounter(this.id);" 
       onblur="javascript:CharCounter(this.id);"></asp:TextBox>
     <asp:Label ID="MessageLabel" runat="server" Text="100 chars remaining">
     </asp:Label>
    </div>
 
    </form>
</body>

Place this script in the header tag.

 <script language="javascript" type="text/javascript">
    function CharCounter(CharacterCountTextBox) {
     var totalchar = '<%= CharacterCountTextBox.MaxLength %>';
     var txtbox = document.getElementById(CharacterCountTextBox);
     var lbl = document.getElementById('<% =MessageLabel.ClientID %>');
     if (txtbox.value.length > totalchar) {
       txtbox.value = txtbox.value.substring(0, totalchar);
         }
     lbl.innerText = (totalchar - txtbox.value.length) + " chars remaining";
        }
</script>

0 comments:

Post a Comment

Vikram Chandra Theme by BloggerThemes & NewWPThemes Sponsored by iBlogtoBlog