Blog

Count the characters while entering in TextBox using Javascript

Posted by Senthilkumar Blogs | JavaScript Apr 04, 2012
It explains about the Count the characters while entering in TextBox using Javascript.
Design:

 <table cellpadding="0" cellspacing="0" border="0" width="100%">
            <tr>
                <td>
                    <asp:TextBox ID="txtComments" BackColor="Gray" ForeColor="White" runat="server" TextMode="MultiLine" onkeyup="return CountCharacters();" Width="400px" Height="75px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td style="padding-top:10px;">
                    Characters remaining:&nbsp;<asp:TextBox ID="txtRemain" BackColor="Gray" ForeColor="White"  runat="server" Text="200" Width="45px"></asp:TextBox>
                </td>
            </tr>
        </table>


JavaScript:

<script type="text/javascript">
    
    function CountCharacters()
    {
        var maxSize = 200;
        
        if(document.getElementById('<%= txtComments.ClientID %>'))
        {
            var ctrl =document.getElementById('<%= txtComments.ClientID %>');
            var len = document.getElementById('<%= txtComments.ClientID %>').value.length;
            if(len <= maxSize)
            {
                var diff = parseInt(maxSize) - parseInt(len);
                
                if(document.getElementById('<%= txtRemain.ClientID %>'))
                {
                    document.getElementById('<%= txtRemain.ClientID %>').value = diff;
                }
            }
            else
            {
                ctrl.value = ctrl.value.substring(0,maxSize);
            }
        }
        
        return false;
    }
    </script>


Screenshot:
txtRemain.jpg
COMMENT USING
PREMIUM SPONSORS
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.
SPONSORED BY
  • MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.
Employers - Post Free Jobs