22 Votes

Textarea Maxlength: Limit Maximum Number of Characters in Textarea

Tutorial by Stefan Trost | Last update on 2021-05-07 | Created on 2013-03-10

Unfortunately, the HTML specification allows the maxlength attribute only for text input boxes but not for text fields or text areas. If we also want to limit the maximum number of characters that can be entered by a user in a textarea, we need to use JavaScript. How to do that, I'll show you today.

For that, I want to show you an example for jQuery, which is simultaneously indicating the number of characters left.

HTML

We would like to design the HTML code in such a way that we can use the maxlength attribute in the same way as we are used to from other text fields:

<div>
   <textarea name="text" maxlength="100"></textarea>
   <p>Remaining characters: <span class="charsleft">100</span></p>
</div>

Below the text field we want to show the user how many characters are still available. For this we install a placeholder by marking the area in which the number should appear later with the class "charsleft". We can then simply address this area later and output the remaining characters. At the beginning, of course, the number of characters available should be displayed here (in our example 100).

In our example we have placed the placeholder on a line beginning with "Remaining characters:". Of course, we also have any other design options available here. Only the principle should be clarified using the example.

However, it is important for the example that both the text field and the placeholder are arranged in the same superordinate DIV container. In this way, the assignment between the text area and the display takes place later. It is thus also possible to operate several text fields in parallel on one page. If this is not necessary, you could of course also give our placeholder area a unique ID and use it to address it.

jQuery

But now we come to the most important part of our tutorial: The heart is our jQuery code that makes sure to limit the number of characters and to carry out the display.

$(document).ready(function() {
   $('textarea[maxlength]').keyup(function(){
      var max = parseInt($(this).attr('maxlength'));

      if($(this).val().length > max){
         $(this).val($(this).val().substr(0, max));
      }
	 
      $(this).parent().find('.charsleft').html(max - $(this).val().length);
   });	
});

The check and the display of the remaining characters should be carried out every each time, the user releases a key (keyup).

First, we catch the value of the maximum number of characters allowed from the maxlength-attribute in order to store this value in the variable "max". After that, we look up whether the length of the characters written in the text box exceeds the maximum number of characters allowed. If so, we cut off the extra characters.

Finally, we are searching for the "charsleft" section in order to set it to the number of remaining characters (maximum number of characters - the number of characters in the field). As already mentioned above, this search works via the parent container of the text field. If we would like to work with an ID instead, the line could also be replaced by $('#charsleft').html(max - $(this).val().length), the placeholder area correspondingly <span id = "charsleft">.

Warning

Since we carry out all checks on the client side with JavaScript, we cannot trust the data that reaches us after submitting the form so that we should check the actual length of the user input in our PHP code. For example, if a user has deactivated JavaScript, neither the display of the remaining characters nor the character limit in the textarea will work. This situation does not differ from conventional text fields with a maxlength attribute - these can also be easily manipulated on the user side and should therefore always be checked again at the server level, too.

ReplyPositiveNegativeDateVotes
Avatar
26 Votes

A small suggestion from me:

Alternatively, you can also use the line

$('textarea[maxlength]').keyup(function(){

instead of the line:

$('textarea[maxlength]').bind('input propertychange',
function(){ 

It is both working.
2013-03-11 at 16:51

ReplyPositive Negative
Avatar
-15 Votes

A line break in the value is canonicalized by the browser to CR LF (carriage return, linefeed, i.e. two control characters).

The counter only counts the linebreak as one character, thus not displaying properly how many character are left when the input contains line breaks.
2013-05-23 at 18:40

ReplyPositive Negative
Avatar
35 Votes

Apparently, jQuery seems to strip "genuine" linefeeds from the value returned by .val().

Adding this workaround to your jQuery code works for me:

$.valHooks.textarea = { get: function(e) {
  return e.value.replace(/\r?\n/g, "\r\n");
}};

I have created a jsFiddle for demonstration.
2013-05-23 at 19:05

Positive Negative
Reply
Reply

About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.