Welcome to Hellrocker's Collections

Hope its all of some use to computer users.............

Tuesday, November 23, 2010

Character counter with limit facility

Ever stuck with requirement to count the characters in a textbox in real time. Here is the simplest solution... Just use this JavaScript and you are done...

Step 1: Put the following script in head section of your page (htm, asp, aspx, php....)

<script type="text/javascript">
        var count = "250";
        var len = "0";
        function limiter() {
            var tex = document.form1.txtmailmsg.value;
            len = tex.length;
            if (len > count) {
                tex = tex.substring(0, count);
                document.form1.txtmailmsg.value = tex;
                document.getElementById("limit").innerHTML = len;
                return false;
            }
            document.getElementById("limit").innerHTML = len;
        }
</script>

Step 2: Create a textbox or input - type text or textarea or what ever you may call it.

Step 3: Call the function on "onKeyUp" event of the desired textbox.

<asp:textbox id="txtmailmsg" onkeyup="limiter()" runat="server" textmode="MultiLine"></asp:textbox>

Step 4: Put the following script at the desired place to display the counter

<script type="text/javascript">
          document.write("<label id=limit>" + len + "</label>");
</script>

And you are done with the counter/limiter for your textbox.

Note: The reason to create label using JavaScript is to display the default number of character even for the first time as soon as page loads. If you don't need this, just put a simple label with id="limit"

Found it useful, please provide your comments...

0 comments:

Post a Comment