Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome counts characters wrong in textarea with maxlength attribute

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:

imgur

like image 977
Roman Pominov Avatar asked Apr 05 '12 14:04

Roman Pominov


People also ask

Which attribute is used to limit the text to be given in the textarea Maxlength?

The maxlength attribute defines the maximum number of characters (as UTF-16 code units) the user can enter into an <input> or <textarea> . This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the input or textarea has no maximum length.

What is Maxlength in textarea?

The maxlength attribute specifies the maximum length (in characters) of a text area.


2 Answers

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/

$(function () {     $('#test').keyup(function () {         var x = $('#test').val();          var newLines = x.match(/(\r\n|\n|\r)/g);         var addition = 0;         if (newLines != null) {             addition = newLines.length;         }          $('#length').html(x.length + addition);     }) }) 

Basically you just count the total line breaks in the textbox and add 1 to the character count for each one.

like image 74
Tim Avatar answered Sep 28 '22 07:09

Tim


Your carriage returns are considered 2 characters each when it comes to maxlength.

1\r\n 1\r\n 1\r\n 1 

But it seems that the javascript only could one of the \r\n (I am not sure which one) which only adds up to 7.

like image 20
Naftali Avatar answered Sep 28 '22 08:09

Naftali