2

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

hcharge
  • 1,216
  • 2
  • 24
  • 43

1 Answers1

3

Try

$lengthOfText = $this.val().replace(/\n/g, '').length

Instead of

$lengthOfText = $this.val().length

This way you'll get rid of new line characters in textarea.

If you want all kind of spacing avoided from total count, you can use

$lengthOfText = $this.val().replace(/\s/g, '').length

Hope this helps.

nisargjhaveri
  • 1,469
  • 11
  • 21
  • That looks to have done the trick, thank you very much. I knew it'd be a regex but was trying this "\r\n?|\n" from here http://stackoverflow.com/questions/3219014/what-is-a-cross-platform-regex-for-removal-of-line-breaks – hcharge Aug 29 '14 at 15:25
  • I'm not sure if my solution works on windows or not. This also works, and maybe is cross platform, too. `$this.val().replace(/\r\n?|\n/g, '').length` – nisargjhaveri Aug 29 '14 at 15:31
  • Your first one seems to work in Windows, if I do find any problems in other browsers I'll try your other regex, thanks again. – hcharge Aug 29 '14 at 15:40