Chrome counts characters wrong in textarea with maxlength attribute

ε祈祈猫儿з 提交于 2019-12-17 02:10:43

问题


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:


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.

var len = $('#test').val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;

Then use that variable to display the length of the textarea value, or limit it, and so on.




回答5:


It looks like that javascript is considering length of new line character also.

Try using:


var x = $('#test').val();

x = x.replace(/(\r\n|\n|\r)/g,"");    

$('#length').html(x.length);

I used it in your fiddle and it was working. Hope this helps.




回答6:


That is because an new line is actually 2 bytes, and therefore 2 long. JavaScript doesn't see it that way and therefore it will count only 1, making the total of 7 (3 new lines)




回答7:


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.

var originalVal = $.fn.val;
$.fn.val = function (value) {
    if (typeof value == 'undefined') {
        // Getter

        if ($(this).is("textarea")) {
            return originalVal.call(this)
                .replace(/\r\n/g, '\n')     // reduce all \r\n to \n
                .replace(/\r/g, '\n')       // reduce all \r to \n (we shouldn't really need this line. this is for paranoia!)
                .replace(/\n/g, '\r\n');    // expand all \n to \r\n

            // this two-step approach allows us to not accidentally catch a perfect \r\n
            //   and turn it into a \r\r\n, which wouldn't help anything.
        }

        return originalVal.call(this);
    }
    else {
        // Setter
        return originalVal.call(this, value);
    }
};



回答8:


If you want to get remaining content length of text area then you can use match on the string containing the line breaks.

HTML:

<textarea id="content" rows="5" cols="15" maxlength="250"></textarea>

JS:

var getContentWidthWithNextLine = function(){
    return 250 - content.length + (content.match(/\n/g)||[]).length;
}



回答9:


var value = $('#textarea').val();
var numberOfLineBreaks = (value.match(/\n/g)||[]).length;
$('#textarea').attr("maxlength",500+numberOfLineBreaks);

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!




回答10:


Textareas are still not fully in sync among browsers. I noticed 2 major problems: Carriage returns and Character encodings

Carriage return

By default are manipulated as 2 characters \r\n (Windows style).

The problem is that Chrome and Firefox will count it as one character. You can also select it to observe there is an invisivle character selected as a space.

A workaround is found here:

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

Jquery word counts when user type line break

Internet explorer on the other hand will count it as 2 characters.

Their representation is :

Binary: 00001101 00001010

Hex: 0D0A

, and are represented in UTF-8 as 2 characters and counted for maxlength as 2 characters.

The HTML entities can be

1) Created from javascript code:

<textarea id='txa'></textarea>

document.getElementById("txa").value = String.fromCharCode(13, 10);

2) Parsed from the content of the textarea:

Ansi code: &#13;&#10;

<textarea>Line one.&#13;&#10;Line two.</textarea>

3) Inserted from keyboard Enter key

4) Defined as the multiline content of the textbox

<textarea>Line one.
Line two.</textarea>

Character Encoding

Character encoding of an input field like textarea is independent than the character encoding of the page. This is important if you plan to count the bytes. So, if you have a meta header to define ANSI encoding of your page (with 1 byte per character), the content of your textbox is still UTF-8 with 2 bytes per character.

A workaround for the character encoding is provided here:

function htmlEncode(value){
  // Create a in-memory div, set its inner text (which jQuery automatically encodes)
  // Then grab the encoded contents back out. The div never exists on the page.
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}

HTML-encoding lost when attribute read from input field



来源:https://stackoverflow.com/questions/10030921/chrome-counts-characters-wrong-in-textarea-with-maxlength-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!