I want to get the string length when a key is pressed like StackOverflow does.

I have tried to do this with onblur, but it’s not working. How do I do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As for the question which event you should use for this: use the
inputevent, and fall back tokeyup/keydownin older browsers.Here’s an example, DOM0-style:
The other question is how to count the number of characters in the string. Depending on your definition of “character”, all answers posted so far are incorrect. The
string.lengthanswer is only reliable when you’re certain that only BMP Unicode symbols will be entered. For example,'a'.length == 1, as you’d expect.However, for supplementary (non-BMP) symbols, things are a bit different. For example,
''.length == 2, even though there’s only one Unicode symbol there. This is because JavaScript exposes UCS-2 code units as “characters”.Luckily, it’s still possible to count the number of Unicode symbols in a JavaScript string through some hackery. You could use Punycode.js’s utility functions to convert between UCS-2 strings and Unicode code points for this:
P.S. I just noticed the counter script that Stack Overflow uses gets this wrong. Try entering
, and you’ll see that it (incorrectly) counts as two characters.