1

I am trying to display a "x characters left" text next to a textarea, to see how much still can be written, with javascript / jquery:

var area = 'textarea#zoomcomment';
var c = $(area).val().length;

Then the input is validated with laravel's max validation.

'comment' => 'required|max:3000'

The javascript does not count the \n or \r characters, but PHP/laravel does. Is there a javascript function to count everything , including linebreaks etc ? I'd like to have the same string length with js and php.

edit:

it seems, that javascript/jquery counts \n\r as 1 and php strlen() counts it as 2 characters. I tried to avoid jquery, but it still seemed to count wrong :(

        var c = document.getElementById('zoomcomment').value.length;
        alert(c);

this question has a good answer

Community
  • 1
  • 1
haheute
  • 2,129
  • 3
  • 32
  • 49
  • Are you sure the `\n` and `\r` characters are not being counted? [It seems to be working fine on Firefox at least.](http://jsfiddle.net/vcny46hd/) – Zsw Oct 14 '15 at 07:09
  • ok. yes it seems to count right, when typing, i see... but when i copypaste a 3000 character text from http://www.loremipsum.de/, my js counting function says 3000 characters and php strlen() says 3010. something seems to be wrong – haheute Oct 14 '15 at 10:58
  • i did not see the fiddle, sorry. it alerts with firefox but not in chromium, here – haheute Oct 14 '15 at 11:05

1 Answers1

0

You could do it using html function which gives you innerhtml -

var area = 'textarea#zoomcomment';
var c = $(area).html().length;
Rohit Kumar
  • 1,948
  • 1
  • 11
  • 16