By "word counter" I assume you mean "character counter" since your question talks about characters.
There are two parts to building this counter:
Need a way to count the number of bytes in a UTF-8 string. Thankfully, someone else already answered this question:
encodeURIComponent(text).replace(/%[A-F\d]{2}/g, 'U').length
Need a way to trigger the count function every time the user types something. We can use the keyup
event:
$('textarea').keyup(function () { ... });
Here is a completed example: http://jsfiddle.net/jefferyto/DWwQr/
Update: I guess what you're looking for is a counter that counts down, indicating how many characters left that the user can enter.
Technically this would not be hard to compute, if you make an assumption on how many bytes go into 1 character:
(characters left) = Math.floor((255 - (num bytes in string)) / (num bytes in character))
But this would not be a good idea from a user perspective:
What would you use as num bytes in character
?
If you use 1, then at the beginning the counter would say 255, but that's only true for ASCII characters; the user wouldn't be able to enter 255 Chinese characters.
Any number you choose would not be correct for a portion of your users.
When the user starts entering text, the counter will not count down 1 by 1, as the user would expect, but rather in incomprehensible steps (incomprehensible to the user).
Again assuming 1 byte per character for the calculation, before the user has entered any text, the counter will say 255. If the user enters a 4-byte character, the counter would change to 251.
It makes no sense to the user that they entered 1 character but the counter decreased by some other number.
I suggest using VARCHAR instead of TINYTEXT; the length of a VARCHAR field is defined with a number of characters instead of bytes. Doing so means your character count can be stable and correct.