Input character counter using simple JQuery

Input character counter using simple JQuery

Character counter mechanisms in input fields can help you determine some very important validation checks. Suppose you have text fields and text areas where you do not want the user to exceed a particular number of characters; this validation will help prompt the user that he or she has exceeded the limit.

There are various uses of this short snippet. For example –

  1. Major Websites with the likes of Twitter, Pinterest, etc. limit their user bio fields to some particular characters. In fact, the tweet character counter of Twitter is the most relevant example. As soon as the user crosses the limit, the counter goes red.
  2. When you are running a database driven application, it might happen that you need to limit your field character counter to a certain value. This helps maintain the database’s stability.

Suppose your database address field has a varchar limit set to 200. Now, if the user enters a huge text that crosses 200 characters, the rest will be cut off by the database. So, it would be best to prompt it to the user in the front end.

  1. Mathematical tracking and calculating systems can actually track how many characters have been inputted by the user. This becomes useful when you modify the character counter procedure to calculate targeted character types.

Suppose you count the number of characters except for spaces, or you count the number of numeric characters, and so on.

Character counter mechanism from scratch

There might be some good plugins and snippets around the Internet that does character counting. But, I thought I must give a detailed approach towards the process.

Character counter techniques won’t be too hard to follow for people who are already quite used with JQuery methods and usage of JQuery.

input-character-count-instant-update-using-simple-jquery-demo

I will detail every individual step involved in this procedure so that you can manipulate and modify the required steps to create a counting method of your own.

Counting total number of characters

In order to get a character counter of all the input a user makes, we must directly start off catching all the input and just counting each time the keystroke is made.

So, for that we prepare an HTML text-area and attach a JQuery key-up event to it. So, as soon as a key is pressed and released – our character counter increases by one.

The result shall be displayed and updated instantly on a different panel on the same webpage. Let’s try –

  • 0
    characters
  • 0
    spaces
  • 0
    numbers
  • 0
    alphabets

The above is the HTML structure of our webpage. In order to perfect our character counter algorithm we need to follow a stringent procedure. The concept is very easy. We must count the number of characters present at a particular time in the text-area.

We could have done it very simply using just the keyup event and adding or subtracting the character counter. In that case, we have some very acute cases where we would not be able to defer the complexity –

  1. If the user starts deleting with the delete key at the end of the line, the keyup event shall be called and the character counter shall get deducted. But, the final result will be incorrect.
  2. Another issue is that we will be able to correctly determine the number of alphabets, numbers, etc when the characters get added. But, when deletion starts, we would fail to keep track correctly.

For many such similar error issues, I have taken a different approach. My approach is as follows –

  1. We collect the whole string each time when the keyup event is fired. Thus, ensuring that we update character counter results immediately. On keyup() event the program collects the textarea value using the val() method.
  2. Next we perform the required counting mechanisms using the string as a character array. I have used the split() method for this step.
  3. Individual calculations like number of spaces, alphabets, numbers etc. are calculated each time through custom methods.
  4. The evaluated values are displayed to the HTML structure using the html() JQuery function.   

Now that you know the workflow, have a look at the JQuery code –

var total = 0;var spaces = 0;var alphabets = 0;var numbers = 0;var vowels = 0;
    var str = new Array();
    
    $(".textinput").keyup(function(e){
      if((e.keyCode>=32 && e.keyCode<=127) || e.keyCode === 8){  
        str = $(".textinput").val().split("");
        total = str.length;
        spaces = findSpaces(str);
        alphabets = findAlphabets(str);
        numbers = findNumbers(str);
        $("ul.outputbox li").eq(0).find("span").html(total);
        $("ul.outputbox li").eq(1).find("span").html(spaces);
        $("ul.outputbox li").eq(2).find("span").html(numbers);
        $("ul.outputbox li").eq(3).find("span").html(alphabets);
        if(total>50){
            $("ul.outputbox li").find("span").css('color','#ce0f1d');
        }
        else{
            $("ul.outputbox li").find("span").css('color','#70b60b');
        }
      }
    });

Custom functions for customized character counter

As you can see, I have implemented two custom functions in order to find out how many alphabets, numbers and spaces are present in our text.

The calculation for this is very simple. Have a look at the functions below. These are the functions that I have called in the above mentioned JQuery code.

function findSpaces(str){
    var s=0;
    for(var i=0;i<str.length;i++){
        if(str[i] === ' '){
             s++; 
        }
    }
    return s;
}

function findAlphabets(str){
    var a=0;
    for(var i=0;i<str.length;i++){
        if((str[i].charCodeAt(0)>=65 && str[i].charCodeAt(0)<=90) || (str[i].charCodeAt(0)>=97 && str[i].charCodeAt(0)<=122)){
             a++; 
        }
    }
    return a;
}

function findNumbers(str){
    var n=0;
    for(var i=0;i<str.length;i++){
        if(str[i].charCodeAt(0)>=48 && str[i].charCodeAt(0)<=57){
             n++; 
        }
    }
    return n;
}

For spaces, I just run a loop and matched whether the current index character is space or not. This is a simple character comparison using conditional statements.

For alphabets, I cannot do the above step. So, what I did was I used the charCodeAt() method of JavaScript to find out the ASCII code of the current index character. Once it is done, I just checked whether the ASCII code falls within the alphabet range of ASCII codes or not. If yes then alphabet counts increase otherwise decreases.

NOTE: An important fact for you to understand here is that I just mentioned increasing space count and increasing alphabet count. What about decreasing? What happens when the user deletes an alphabet or space? Does our count get updated?

YES, IT DOES!   

Now we shall understand how. I have previously mentioned in this article that we are working with the whole string each time the event is fired. The only reason for that is this situation. When the above functions are called they have the facility to only add count.

Because when a user deletes a character, I can never track what that was- a space, number or alphabet. So, it’s best to take the fresh string after the character is deleted and calculate again.

Okay, now for the number count, we simply follow the same step. We create a method and call it to match whether the characters fall into the ASCII range of numbers or not.

That’s it. Do view the demo and don’t forget to share. You can also include your suggestions in the comment box. Further, you can also alter this code to get more filtered results like no. of vowels, consonants, special characters, etc.

  • Lorane Rhoden

    Maybe I need to put this on My Blog :-) This will cut out those spammers who like to post long unnecessary things

  • Roberts

    Hi, I am Vanessa Ally. Yes, you are right indeed, there are some sites that don’t allow more than 200 or 300 characters in a description and I find it annoying. Your method that you present here is a great facility for us, the bloggers!

    • Yes @disqus_wAbQzo6hmO:disqus , this is an effective means to cut short long unnecessary phrases

  • Tim

    Very cool; thanks for this information as I can think of numerous ways this could come in handy.

  • Joanna Sormunen

    Thank you for the information! I have so much to learn about the technical side of blogging still.

    • @joannasormunen:disqus you’re welcome. I hope it works great for you

  • Loudthinkin

    It’s important to put check on those words! :) we use this software frequently in my work setup.

  • anna

    Oh how I wish I could make you materialise (like a genie :) ) whenever I encounter computer annoyances. Wish I had your knowledge !! Great post !

  • Usually when I’ve found a new blogger template, I opened the template section for realigning the template for my uses. I always encounter this JQuery but I don’t know on how to use. I know some html only. Thanks for sharing this article.

  • Good tech tip! I wish I was as good with codes!

  • Michelle @ Vitamin Sunshine

    That could be really helpful in reducing long spam comments! Thanks for the tip.

  • Sin Yee

    I seriously cannot understand all… Code = alien words for me. Have to learn more about it now.

  • papaleng

    Learned something new today. Honestly I am no techie man but I do believe that shorts are indeed very helpful in social media specially in Tweeter.

  • dmhyf

    I am not a techie person and this post is quite technical. I am pretty sure though that it is very important for those who want to limit how long people comment on their posts.

  • kaka16

    It is good to learn something new today and this JQuery codes is really interesting – KarenT