Search code examples
javascriptjqueryhtmlcountdown

How do I create a textarea countdown with jQuery?


I'm working on this survey form, and I'm trying to code a comment area that has a character limit of 500. From what I've seen, I'm doing everything "right", but clearly I must be overlooking something.

Here is my jsFiddle.

HTML

<span class="char-remain">500 Characters remaining</span>
<textarea class="comment" rows="10" cols="50" maxlength="500">Enter Text Here</textarea>

jQuery

comment = $(".comment");             

comment.on("keyup change", function(){

   charCount = $(this).text().length;
   charRemain = 500 - charCount;

   $(this).prev("span").text("(" + charRemain + ")");

   alert(charRemain + "Characters Remaining");

});

The alert is there really for me to see if it's working or triggering at all, which it isn't. What am I missing?


Solution

  • You have an error in the first line.

    $(document).ready(function {
    

    Only change to:

    $(document).ready(function() {
    

    As you're trying to get the length of the comment field, you need to use the .val() function. It's an equivalent to .value in plain JavaScript.

    However, you can optimize your code by using the next:

    var maxlength = parseInt(comment.attr("maxlength"), 10);
    

    The code above will store the comment's field maxlength. So you might try with:

    $(document).ready(function() {
      var comment = $(".comment");
      var maxlength = parseInt(comment.attr("maxlength"), 10);
    
      comment.on("keyup keypress change", function() {
        charCount = $(this).val().length;
        charRemain = maxlength - charCount;
        //$(this).prev().prev("span").text(charRemain + " Characters remaining");
        $(".char-remain").text(charRemain + " Characters remaining");
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <span class="char-remain">500 Characters remaining</span>
    <br />
    <textarea class="comment" rows="10" cols="50" maxlength="500">Enter Text Here</textarea>

    As suggested @TiesonT. in the comments, you could easily get the span content by using:

    $(".char-remain").text(charRemain + " Characters remaining");
    

    In this context you don't need to worry about tags between the comment field and the span content.

    Updated:

    You might bind with the keypress event to get the current length while the user is pressing a key.

    comment.on("keyup keypress change", function() {