SyntaxStudy
Sign Up
jQuery Beginner 3 min read

Character Counter

Character Counter

Show a real-time character count for textareas. Change the counter color when approaching the limit.

Example
const MAX = 280;
$("#tweet").on("input", function() {
  const used = $(this).val().length;
  const left = MAX - used;
  $("#counter")
    .text(left)
    .toggleClass("text-danger", left < 20)
    .toggleClass("text-warning", left >= 20 && left < 50);
  $("button[type=submit]").prop("disabled", left < 0);
});
Pro Tip

Disable the submit button when over the character limit — do not just show an error.