Looking to Build/Redesign a Website or Blog ?

To speak to Rakshit, call +91 968 704 2303

Maximum Charactors/Words limit(counter) for textarea using Javascript/jQuery

Hello Friends,

Are you looking for limiting charactors/words entered in textarea? Today i need to implement the limit for description field where customer can only enter upto 255 charactor. If customer entered 255 charactors than i have to restrict customer from entering more charactors in textarea field. I came across below javascript/jQuery function using which i can easily restrict customer to enter limited charactors/words.

For implementing above functionality, follow the below steps.

1) Download latest jQuery and include it in your html/php file.
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>

2) Copy below code and paste it into your javascript file.
 

$(document).ready(function(){

 $('.char_limit').each(function(){
     // maximum limit of characters.
     var maxlimit = 255;
     // current number of characters
     var length = $(this).val().length;
     if(length >= maxlimit)
     {
           $(this).val($(this).val().substring(0, maxlimit));
           length = maxlimit;
       }
 
  // update count on page load
  $(this).parent().find('.count').html( (maxlimit – length) + ' characters left');
     // bind on key up event
     $(this).keyup(function(){
  // get new length of characters
 
  var new_length = $(this).val().length;
 
  if(new_length >= maxlimit)
  {
    $(this).val($(this).val().substring(0, maxlimit));
    //update the new length
    new_length = maxlimit;
   }
 
  // update count
  $(this).parent().find('.count').html( (maxlimit – new_length) + ' characters left');
     });
 });

});

3) Add "char_limit" class in your textarea field.
<textarea class="char_limit" rows="5" cols="40"></textarea>

4) If you would like to show live counter than add count class in span tag as below.
<span class="count"></span>

Thats it.

If you find any problem in this than let me know by comment.

To know more about programming,JavaScript issues,jQuery,Expression Engine,MYSQL database and Open-source, enter your email address below. We will send you free tutorials.

Enter your email address:
 
Feel free to ask any question. Just leave your comment below and we will answer your comment with in 24 hours.
Share:

No Comments Yet.

Leave a Reply

Your email address will not be published.