0

I have a word counts create in jquery.

http://jsfiddle.net/DqYsN/

However if user press 'Enter'(line break), it will cause 1 character left.

ex.maxlength=10, if user type abcde, \n, abc

total become 9 characters only and the div show 1 character left

$(document).ready(function(){   
    //Word Count
        $('.word_count')
        .on('input keyup keydown focus', function () {
            var maxlength = $(this).attr('maxlength');
            var value = $(this).val();

            if(value.length > 0) {
                $(this).nextAll('div').first().text((maxlength - $(this).val().length));
            } else {
                $(this).nextAll('div').first().text(maxlength);
            }   
        }); 
});

i just find out Chrome count characters wrong in textarea

Chrome counts characters wrong in textarea with maxlength attribute

Community
  • 1
  • 1
user2178521
  • 833
  • 1
  • 14
  • 26

3 Answers3

1

You can find the exact character length like this (excluding any space and line breaks)

var length = $.trim($(this).val()).split(" ").join("").split('\n').join('').length;

Demo -----> http://jsfiddle.net/DqYsN/1/

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
1

Chrome count line break as 2 characters, put this one inside of your code should be fine.

var isChrome = window.chrome;
if(isChrome){var value = $(this).val().replace(/(\r\n|\n|\r)/g,"  ");}
else{ var value = $(this).val();}

" " this make length 2 characters, so it will match with textarea length in chrome

Benjamin W
  • 2,658
  • 7
  • 26
  • 48
0

You can replace the whitespaces before counting with something like: .replace(/\s/,'')

So instead of:

$(this).val().length)

You do:

$(this).val().replace(/\s/,'').length)
Francisco Paulo
  • 6,284
  • 26
  • 25