MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Create an Input Character Counter with jQuery

We will learn today on the process to restrict the number of characters permissible to be entered into an input field using jQuery and Google JSAPI.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

We have a snippet below which can be made use of to incorporate in your projects in order to achieve the similar outcome like this. It helps in giving a counter to the user displaying the number of characters that can be filled further.

Snippet to be incorporated

Figure 1: Snippet to be incorporated

This could be extended in a simpler manner in order to make it run on multiple input areas, or even as a jQuery plugin.

A look at the Code, the Javascript

Listing 1: Represents the JavaScript Code

<script type="text/javascript" src="http://www.google.com/jsapi"></script>  
  
<script type="text/javascript" language="javascript">  
google.load("jquery", "1.4.2");  
  
var characterLimit = 150;  
  
google.setOnLoadCallback(function(){  
      
    $('#remainingCharacters').html(characterLimit);  
      
    $('#myInputarea').bind('keyup', function(){  
        var charactersUsed = $(this).val().length;  
          
        if(charactersUsed > characterLimit){  
            charactersUsed = characterLimit;  
            $(this).val($(this).val().substr(0, characterLimit));  
            $(this).scrollTop($(this)[0].scrollHeight);  
        }  
          
        var charactersRemaining = characterLimit - charactersUsed;  
          
        $('#remainingCharacters').html(charactersRemaining);  
    });  
}); 
</script>   

The HTML

Listing 2: Represents the HTML Code

<Inputarea id="myInputarea"></Inputarea>  
<p><span id="remainingCharacters"></span> characters remaining.</p>  

How the above Code works?

We will start with HTML markup first which is pretty simple where we are merely coming up with an Inputarea, with an ID of myInputarea. There will be one paragraph beneath the same comprising of an empty span and an ID of remaining Characters. This is the area where our intention is to display the remaining characters to the user as and when they are entering.

Google JSAPI

Let us go step by step since we have a Javascript that is a little more involved.

<script type="text/javascript" src="http://www.google.com/jsapi"></script>  

Let us see the benefits of making use of Google JSAPI which is preferred over anything in order to load jQuery:

  • This is always hosted in the same place. This way there will be no one having to traverse your own paths in order to trace where your JS libraries are stored.
  • More than this, it saves bandwidth
  • It also has the advantage of loading at a rapid rate
  • Finally, we have the advantage of it being very easy to bolt on other libraries you may require.
<script type="text/javascript" language="javascript">  
google.load("jquery", "1.4.2");  

Let us take a look at the main Javascript block, and then making use of the Google JSAPI, the jquery library is loaded.

Variable Limit

var characterLimit = 150;  

All it says is, we are setting a global variable to the value of our maximum permissible for the Input area field and one can change or modify to whatever you wish.

What? No $(document).ready()?
google.setOnLoadCallback(function(){  

In case you are making use of Google JSAPI, then google.setOnLoadCallback() should be used at any cost. And the only reason for doing the same is the way we’re loading the jQuery. $(document).ready() may actually give you with a false-positive, implements or run prior to jQuery has been loaded completely. This is for the reason that we should use the google on load callback that is capable of firing once all the libraries that have been requested have been included.

Set the Starting Figure

$('#remainingCharacters').html(characterLimit);  

For the reason that the remainingCharacters span in our HTML markup is empty, it is required to set the value when the page is loaded. The value of the leftover characters can be hard-code which will then mean that there will be a need to update two places in case someone wants to modify the restriction or the maximum permissible limit, not just one (the one place we it is required to modify the character limit is on the var characterLimit = 150; line).

Binding It All Up

Listing 3: Binding a function to ‘keyup’ event

$('#myInputarea').bind('keyup', function(){  
    var charactersUsed = $(this).val().length;  
      
    if(charactersUsed > characterLimit){  
        charactersUsed = characterLimit;  
        $(this).val($(this).val().substr(0, characterLimit));  
        $(this).scrollTop($(this)[0].scrollHeight);  
    }  
      
    var charactersRemaining = characterLimit - charactersUsed;  
      
    $('#remainingCharacters').html(charactersRemaining);  
});  

This is the bind where all magic is to take place, where in firstly we’re binding a function to the ‘keyup’ event on the element named myInputarea. And then inside this function one need to be aware on the number of characters that have been used which is done by calling the following:

var charactersUsed = $(this).val().length;  

It can be noticed how we can use $(this) to reference the myInputarea element.

Listing 4: Code verifying the maximum permissible value

if(charactersUsed > characterLimit){  
    charactersUsed = characterLimit;  
    $(this).val($(this).val().substr(0, characterLimit));  
    $(this).scrollTop($(this)[0].scrollHeight);  
}  

The above statement is used to verify whether the number of characters used is greater than the present character maximum permissible value.

In case if this is greater, it will be obvious that the user has gone over their limit and something needs to be done in this case. Any extra characters would be required to trim once they have exceeded the limit and reset the focus to the bottom of the Input area. We need to set the focus to the bottom again for the reason that the moment you update the text within a Inputarea, the focus jumps back to the top!

Allowing the User to see the Count of Characters Remaining

var charactersRemaining = characterLimit - charactersUsed;  
      
$('#remainingCharacters').html(charactersRemaining);  

Here we kind of perform a quick calculation so as to identify the count of characters remaining, and then update the remainingCharacters span. This will allow the user to see how much more they can enter in the field. This is updated every time you release a key from within the Inputarea.

Sample Output:

Displays the example of this tutorial

Figure 2: Displays the example of this tutorial

Conclusion:

This brings us to an end of this tutorial where we understand how to restrict the user from entering the characters more than the maximum permissible value of the Input area field.



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login