Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>By "word counter" I assume you mean "character counter" since your question talks about characters.</p> <p>There are two parts to building this counter:</p> <ol> <li><p>Need a way to count the number of bytes in a UTF-8 string. Thankfully, someone else already <a href="https://stackoverflow.com/a/2848483/311572">answered</a> this question:</p> <pre><code>encodeURIComponent(text).replace(/%[A-F\d]{2}/g, 'U').length </code></pre></li> <li><p>Need a way to trigger the count function every time the user types something. We can use the <code>keyup</code> event:</p> <pre><code>$('textarea').keyup(function () { ... }); </code></pre></li> </ol> <p>Here is a completed example: <a href="http://jsfiddle.net/jefferyto/DWwQr/" rel="nofollow noreferrer">http://jsfiddle.net/jefferyto/DWwQr/</a></p> <hr> <p><strong>Update:</strong> I guess what you're looking for is a counter that counts <em>down</em>, indicating how many characters left that the user can enter.</p> <p>Technically this would not be hard to compute, if you make an assumption on how many bytes go into 1 character:</p> <pre><code>(characters left) = Math.floor((255 - (num bytes in string)) / (num bytes in character)) </code></pre> <p>But this would not be a good idea from a user perspective:</p> <ol> <li><p>What would you use as <code>num bytes in character</code>?</p> <p>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.</p> <p>Any number you choose would not be correct for a portion of your users.</p></li> <li><p>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).</p> <p>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.</p> <p>It makes no sense to the user that they entered 1 character but the counter decreased by some other number.</p></li> </ol> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload