Friday, March 15, 2013

How to Create a Textarea Character Counter / Limiter Using jQuery

Are you need to limit the number of characters that are allowed to be inserted into Textbox or Textarea? You have seen in various sites(mostly sms sites like way2sms, 160by2) where you can type only a fix number of characters into textbox. Here, I am going to show you a simple jQuery snippet that you can use to achieve this functionality.

In previous posts, I explained Animated Sliding Recent Post Widget For Blogger, Change Input to Upper Case using Java Script, Calculate Age from Date of Birth Using Java Script, jQuery .toggleClass() example, jQuery Draggable Div Example in ASP.Net, jQuery Resizable Div Example in ASP.Netand some other articles related to jQuery, Java Script etc.


Creating a textarea character couter using jQuery is pretty easy.To implement this we need to write the code like as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestOCRReader.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var characterLimit = 140;
        $(document).ready(function () {
            $("#lblremaingCharacters").html(characterLimit);
            $("#meTextarea").bind("keyup", function () {
                var characterInserted = $(this).val().length;
                if (characterInserted > characterLimit) {
                    $(this).val($(this).val().substr(0, characterLimit));
                }
                var characterRemaining = characterLimit - characterInserted;
                $("#lblremaingCharacters").html(characterRemaining);
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <label id="lblremaingCharacters" style="color:Red;font-weight:bold"></label><label> characters remaining.</label><br />
    <textarea id="meTextarea"></textarea>
    </div>
    </form>
</body>
</html>

Live Demo-



No comments:

Post a Comment

^ Scroll to Top