Here is an example:
$(function() {
$('#test').change(function() {
$('#length').html($('#test').val().length)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id=test maxlength=10></textarea>
length = <span id=length>0</span>
Fill textarea with lines (one character at one line) until browser allows. When you finish, leave textarea, and js code will calculate characters too.
So in my case I could enter only 7 characters (including whitespaces) before chrome stopped me. Although value of maxlength attribute is 10:
works perfectly on google already in IE have to avoid the script! In IE the 'break-line' is counted only once, so avoid this solution in IE!
Here's a more universal solution, which overrides the jQuery 'val' function. Will be making this issue into a blog post shortly and linking here.
It looks like that javascript is considering length of new line character also.
Try using:
I used it in your fiddle and it was working. Hope this helps.
It seems like the right method, based on Pointy's answer above, is to count all new lines as two characters. That will standardize it across browsers and match what will get sent when it's posted.
So we could follow the spec and replace all occurrences of a Carriage Return not followed by a New Line, and all New Lines not followed by a Carriage Return, with a Carriage Return - Line Feed pair.
Then use that variable to display the length of the textarea value, or limit it, and so on.
For reasons unknown, jQuery always converts all newlines in the value of a
<textarea>
to a single character. That is, if the browser gives it\r\n
for a newline, jQuery makes sure it's just\n
in the return value of.val()
.Chrome and Firefox both count the length of
<textarea>
tags the same way for the purposes of "maxlength".However, the HTTP spec insists that newlines be represented as
\r\n
. Thus, jQuery, webkit, and Firefox all get this wrong.The upshot is that "maxlength" on
<textarea>
tags is pretty much useless if your server-side code really has a fixed maximum size for a field value.edit — at this point (late 2014) it looks like Chrome (38) behaves correctly. Firefox (33) however still doesn't count each hard return as 2 characters.
Here's how to get your javascript code to match the amount of characters the browser believes is in the textarea:
http://jsfiddle.net/FjXgA/53/
Basically you just count the total line breaks in the textbox and add 1 to the character count for each one.