Count up counter

I use the following little function to count the characters added in a text area:

$("#comment").keyup(function count(){
    counter = $("#comment").val().length;
    $("#count").html(counter);
});

This works well for the purpose. What I am looking for now are the following two functionalities:

  1. There should be a limit of 500 characters that can be added
  2. The button in the form should be disabled until 250 characters are
    reached

I have been searching around but couldn’t find any solution so far. I hope one of the Javascript guru’s here on Sitepoint know how to adjust this function to make this happen.

Thank you all in advance

Hi donboe,

You can do it like this:

<textarea id="comment" maxlength="500"></textarea>
<p>Character count: <span id="charCount">0</span></p>
<button disabled>Continue</button>

and:

var $textField = $("#comment"),
    $charCount = $("#charCount"),
    $button = $("button");

$textField.on("keyup", function(){
  noChars = $("#comment").val().length;
  $charCount.html(noChars);
  if(noChars>10){
    $button.removeAttr('disabled');    
  } else {
    $button.attr('disabled','disabled');  
  }
});

Demo

One thing I would point out is that i this case it makes sense to cache your selectors, as you would otherwise be querying the DOM multiple times whenever a user presses a key.

Hi Pullo. This works great, :smile: Thanks a lot.

How would I cache the selectors?

Thank you in advance

All this means is that you get a reference to them one time and store it in a variable.
My demo does this already :smiley:

:slight_smile: Ha that is what you mean. Understood. I will keep it in mind. Thanks again.