Pages

Friday, January 10, 2014

Limit Number of Characters in TextArea via JQuery

About: In this example we will see how to limit number of characters to be entered in a HTML textarea. To know more about textarea tag, click here.

Pre-requisites:
  1. Knowledge of HTML
  2. Knowledge of JQuery
Introduction: So many times in our application we have to use comment textbox or textarea. In this comment textbox, user can add their comments/views/feedback.
What if we would like to have limited number of characters that users can add in them? For that purpose we can use JQuery as a solution.

Solution:

HTML Code -  Add the following code under body tag of your HTML:

   <span id="remaining">100</span> characters remaining.
    <br />
   <textarea></textarea>


JQuery Code - Add the following code under document.ready function in JQuery:

var maxchars = 100;
        $('textarea').keyup(function () {
            var textAreaLength = $(this).val().length;
            $(this).val($(this).val().substring(0, maxchars));
            textAreaLength = $(this).val().length;
            remaining = maxchars - parseInt(textAreaLength);
            $('#remaining').text(remaining);
        });


Conclusion: You will see that on top of textarea, the number of characters decreases when you enter any character in a textarea. You will also notice that once it reaches zero (0), it will not accept further characters in a textarea.

Note: If you are changing the value of variable "maxchars", don't forget to change the same in span tag. :)




View Sunny Bahree's profile on LinkedIn

No comments:

Post a Comment