I've been banging my head against a wall trying to work out what the best way to get a character countdown from a textarea. I've create this jsfiddle but if I paste in 4000 characters from lipsum.com then it says it's 12 characters over. I know this is because of the line breaks, but I'm unsure on how to get it to work correctly, and consistently across browsers.
$('textarea').on('keyup', function() {
characterCount(this);
});
$('textarea:not(:empty)').each(function() {
characterCount(this);
});
function characterCount(that) {
var $this = $(that),
$maxLength = $this.attr('data-val-length-max'),
$lengthOfText = $this.val().length,
$charCountEl = $this.closest('.form-group').find('.maxchar-count');
if($maxLength) {
$($charCountEl).text($maxLength - $lengthOfText);
}
if($lengthOfText > $maxLength) {
$charCountEl.addClass('has-error');
} else {
$charCountEl.removeClass('has-error');
}
}
And the markup
<div class="form-group">
<textarea rows="5" data-val-length-max="4000"></textarea>
<div>
<span class="maxchar-count">4000</span>
</div>
</div>
I've seen some similar questions but yet to find an answer that works for me.
Thanks
Henry