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.
We weren't happy with any of the purposed solutions.
So we've created a complete char counter solution for JQuery, built on top of jquery-jeditable. It's a
textarea
plugin extension that can count to both ways, displays a custom message, limits char count and also supports jquery-datatables.You can test it right away on JSFiddle.
GitHub link: https://github.com/HippotecLTD/realworld_jquery_jeditable_charcount
Quick start
Add these lines to your HTML:
And then:
Improved version based on Caterham's function:
I was wondering how to do this same thing and taking ideas from everyone here this is what I came up with:
JsFiddle
I created my own jQuery plugin for this task, you can try it out here:
http://jsfiddle.net/Sk8erPeter/8NF4r/
You can create character counters on-the-fly (and also remaining character counters), you can define whether you want to chop text, you can define the suffix texts and you can also define a short format and its separator.
Here's an example usage:
Here's the code of the plugin:
substring()
needs to becomesubstr()
.Example: jsfiddle.net/xqyWV