How to limit characters for textarea including count in jquery

  • 5 years-11 months

    How to limit characters for textarea including count in jquery

    • Category : java
    • Viewed : 18 times
    • Posted On :
    • Posted by : Vikas

    Here are two scenarios where the keyup event will not get fired: The user drags text into the textarea. The user copy-paste text in the textarea with a right click (contextual menu).

    Use the HTML5 input event instead for a more robust solution:

    // jquery
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    
    // html
    <div class="control">
    	<textarea spellcheck="true" maxlength="200" name="question" id="question" class="input-textarea required-entry" cols="5" rows="8" data-validate="{required:true}" aria-required="true"></textarea>
      <div class="limittext"><span class="charnum">200 Characters left</span></div>
    </div>
    
    <script type="text/javascript">
    jQuery(document).ready(function() {
      // edit area start
      var maxLength = 200;
      var textarea_id = "question";
      // edit area end
    
      var html='<span style="color:red;">'+ maxLength + ' characters allowed, excess characters trimmed</span>';
      jQuery("#"+textarea_id).on('input',function(){
          var length = this.value.length;
          if (length >= maxLength) {
            this.value = this.value.substring(0, maxLength);
            jQuery(this).next(".limittext").html(html);
          } else {
            var count=maxLength-length;
            jQuery(this).next(".limittext").html('<span class="charnum">' +count+' Characters left</span>');
          }
      });
    });
    </script>

Report this or Ask your own question

Your Answer

When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
Let's work to help developers, not make them feel stupid.