I want to count characters in a textarea, so I just made:
<textarea id="field" onkeyup="countChar(this)"></textarea>
function countChar(val){
var len = val.value.length;
if (len >= 500) {
val.value = val.value.substring(0, 500);
} else {
$('#charNum').text(500 - len);
}
};
What's wrong with my piece of code? It does not work! Well, that was a newbie handwriting, need a help.
this worked fine for me.
A more generic version so you can use the function for more than one field.
HTML
jQuery
Use the following to skip using else and also skip getting negative count.
Here my example. Supper simple
⚠️ The accepted solution is flawed.
Here are two scenarios where the
keyup
event will not get fired:Use the HTML5
input
event instead for a more robust solution:JavaScript (demo):
And if you absolutely want to use jQuery: