lunes, 27 de noviembre de 2023

Count Textarea Characters with JavaScript


I've been playing around with the Twitter API lately and, as you know, Tweets can only be 140 characters long. I wanted to use a textarea element, not an input type="text", so I couldn't just use maxchars to limit the number of characters. Additionally, I get annoyed when my text is chopped off when pasting. So, what to do? Well, I thought, why not make a little character counter like the one you find on the actual Twitter?

The first step is to create the JavaScript function. I placed mine in a file called count-chars.js and it looks like this:

function countChars(textbox, counter, max) {
  var count = max - document.getElementById(textbox).value.length;
  if (count < 0) { document.getElementById(counter).innerHTML = "<span style=\"color: red;\">" + count + "</span>"; }
  else { document.getElementById(counter).innerHTML = count; }
}

textbox and counter are the IDs of the elements of the textarea we're counting and the span where the count is going to go, respectively.

There's lots you can customize there. You could disable the form if too many characters are entered or you could automatically truncate the text. But, I prefer to just have the warning show up in red text.

The next step is to write the HTML itself:

<script type="text/javascript" src="/js/count-chars.js"></script>
<form action="#" method="POST">
<p>Tweet Something: <span id="char_count"></span><br><textarea name="tweet" id="textbox" class="form-control" rows="3" cols="60" onFocus="countChars('textbox','char_count',140)" onKeyDown="countChars('textbox','char_count',140)" onKeyUp="countChars('textbox','char_count',140)"></textarea></p>
<p><input type="submit" class="btn btn-primary" value="Tweet" /></p>
</form>