Search code examples
javascriptjquerytextareacounter

Javascript or Jquery textarea counter with minimum text length?


I can't find any examples when you want the user to input at least x number of characters in a textarea. There is no max length, only minimum. Is there any simple solutions to this?

This is what I have now.

A simple textarea

<textarea id="textComment" name="comment" ></textarea>

Div area showing x characters remaining to write

<div>Characters left <span id="charsLeft"></span></div>

If possible, disable post button until x characters reached.

<button onclick="frmComment.submit();return false;">Add comment</button>

Solution

  • You can change the minimum length on textarea element => data-minLength="10"

    $(document).ready(function() {
     $("#textComment").on("keyup", function(){
         var minLength = $(this).attr("data-minlength");
         var currentLength = $(this).val().length;
         var remaining = parseInt(minLength) - parseInt(currentLength)
         $("#charsLeft").text((remaining < 0 ? 0: remaining));
         
         if (parseInt(currentLength) < parseInt(minLength))
         {
             $("#commentBtn").prop("disabled", true);
         } else{
             $("#commentBtn").prop("disabled", false);
         }
         
         
     });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <textarea id="textComment" data-minLength="10" name="comment" ></textarea>
    <div>Characters left: <span id="charsLeft"></span></div>
    <button id="commentBtn" disabled onclick="frmComment.submit();return false;">Add comment</button>