How to impose maxlength on textArea in HTML using JavaScript

I would like to have some functionality by which if I write

<textarea maxlength="50"></textarea>
<textarea maxlength="150"></textarea>
<textarea maxlength="250"></textarea>

it will automatically impose the maxlength on the textArea. If possible please do not provide the solution in jQuery.

Note: This can be done if I do something like this:

<textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50">


function imposeMaxLength(Event, Object, MaxLen)
{
return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
}

Copied from What is the best way to emulate an HTML input “maxlength” attribute on an HTML textarea?

But the point is I don't want to write onKeyPress and onKeyUp every time I declare a textArea.

247341 次浏览
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA');


for(var i = 0, l = txts.length; i < l; i++) {
if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) {
var func = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);


if(this.value.length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}


txts[i].onkeyup = func;
txts[i].onblur = func;
}
};


}

还要添加以下事件来处理粘贴到 textarea:

...


txts[i].onkeyup = function() {
...
}


txts[i].paste = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);


if (this.value.length + window.clipboardData.getData("Text").length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}


...

更新 使用 Eirik 的解决方案而不是使用 .live(),因为它更加健壮一些。


即使你想要一个不使用 jQuery 的解决方案,我认为我应该为任何通过 Google 找到这个页面并寻找 jQuery 风格的解决方案的人添加一个:

$(function() {
// Get all textareas that have a "maxlength" property.
$('textarea[maxlength]').each(function() {


// Store the jQuery object to be more efficient...
var $textarea = $(this);


// Store the maxlength and value of the field.
var maxlength = $textarea.attr('maxlength');
var val = $textarea.val();


// Trim the field if it has content over the maxlength.
$textarea.val(val.slice(0, maxlength));


// Bind the trimming behavior to the "keyup" event.
$textarea.bind('keyup', function() {
$textarea.val($textarea.val().slice(0, maxlength));
});


});
});

希望这对你们这些谷歌人有用。

我知道您希望避免使用 jQuery,但是由于解决方案需要 JavaScript,因此此解决方案(使用 jQuery 1.4)是最简洁和健壮的。

Inspired by, but an improvement over Dana Woodman's answer:

这个答案的改变是: 简化和更通用,使用 jQuery.live,如果长度是可以的,也不设置 val (导致 IE 中的箭头键工作,IE 中的显著加速) :

// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').live('keyup blur', function() {
// Store the maxlength and value of the field.
var maxlength = $(this).attr('maxlength');
var val = $(this).val();


// Trim the field if it has content over the maxlength.
if (val.length > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});

EDIT: Updated version for JQuery 1.7 + , using on instead of live

// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').on('keyup blur', function() {
// Store the maxlength and value of the field.
var maxlength = $(this).attr('maxlength');
var val = $(this).val();


// Trim the field if it has content over the maxlength.
if (val.length > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});

HTML5向 textarea元素添加一个 maxlength属性,如下所示:

<!DOCTYPE html>
<html>
<body>
<form action="processForm.php" action="post">
<label for="story">Tell me your story:</label><br>
<textarea id="story" maxlength="100"></textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>

This is currently supported in Chrome 13, FF 5, and Safari 5. Not surprisingly, this is not supported in IE 9. (Tested on Win 7)

Small problem with code above is that val() does not trigger change() event, so if you using backbone.js (or another frameworks for model binding), model won't be updated.

我发布的解决方案对我很有效。

$(function () {


$(document).on('keyup', '.ie8 textarea[maxlength], .ie9 textarea[maxlength]', function (e) {
var maxLength = $(this).attr('maxlength');
if (e.keyCode > 47 && $(this).val().length >= maxLength) {
$(this).val($(this).val().substring(0, maxLength)).trigger('change');
}
return true;
});


});

我最近在 textarea上实现了 maxlength行为,并遇到了这个问题中描述的问题: Chrome 使用 maxlength 属性错误地计算文本区域中的字符数

因此,这里列出的所有实现都不会有什么问题。为了解决这个问题,我在 .length之前添加了 .replace(/(\r\n|\n|\r)/g, "11")。剪绳子的时候要记住。

我以这样的话结束:

var maxlength = el.attr("maxlength");
var val = el.val();
var length = val.length;
var realLength = val.replace(/(\r\n|\n|\r)/g, "11").length;
if (realLength > maxlength) {
el.val(val.slice(0, maxlength - (realLength - length)));
}

不确定它是否能完全解决问题,但是它现在对我有用。

这是我刚刚在我的网站上使用的一些修改过的代码

(对不起 OP 没有请求 jQuery,但是说真的,现在谁不用 jQuery 呢?)

$(function() {
// Get all textareas that have a "maxlength" property.
$("textarea[maxlength]").each(function() {


// Store the jQuery object to be more efficient...
var $textarea = $(this);


// Store the maxlength and value of the field
var maxlength = $textarea.attr("maxlength");


// Add a DIV to display remaining characters to user
$textarea.after($("<div>").addClass("charsRemaining"));


// Bind the trimming behavior to the "keyup" & "blur" events (to handle mouse-based paste)
$textarea.on("keyup blur", function(event) {
// Fix OS-specific line-returns to do an accurate count
var val = $textarea.val().replace(/\r\n|\r|\n/g, "\r\n").slice(0, maxlength);
$textarea.val(val);
// Display updated count to user
$textarea.next(".charsRemaining").html(maxlength - val.length + " characters remaining");
}).trigger("blur");


});
});

Has NOT been tested with international multi-byte characters, so I'm not sure how it works with those exactly.

This solution avoids the issue in IE where the last character is removed when a character in the middle of the text is added. It also works fine with other browsers.

$("textarea[maxlength]").keydown( function(e) {
var key = e.which;  // backspace = 8, delete = 46, arrows = 37,38,39,40


if ( ( key >= 37 && key <= 40 ) || key == 8 || key == 46 ) return;


return $(this).val().length < $(this).attr( "maxlength" );
});

我的表单验证然后处理任何问题,用户可能已经粘贴(似乎只是一个问题在 IE)文本超过最大长度的文本区。

与修剪文本区域的值相比,更好的解决方案。

$('textarea[maxlength]').live('keypress', function(e) {
var maxlength = $(this).attr('maxlength');
var val = $(this).val();


if (val.length > maxlength) {
return false;
}
});

这要容易得多:

<textarea onKeyPress="return ( this.value.length < 1000 );"></textarea>

试试这个 jQuery,它可以在 IE9,FF,Chrome 中工作,并为用户提供倒计时:

$("#comments").bind("keyup keydown", function() {
var max = 500;
var value = $(this).val();
var left = max - value.length;
if(left < 0) {
$(this).val( value.slice(0, left) );
left = 0;
}
$("#charcount").text(left);
});


<textarea id="comments" onkeyup="ismaxlength(this,500)"></textarea>
<span class="max-char-limit"><span id="charcount">500</span> characters left</span>

尝试使用下面的代码示例:

$("#TextAreaID1").bind('input propertychange', function () {
var maxLength = 4000;
if ($(this).val().length > maxLength) {
$(this).val($(this).val().substring(0, maxLength));
}
});

Maxlength 属性在 Internet Explorer 10、 Firefox、 Chrome 和 Safari 中都支持。

注意: 在 Internet Explorer 9和早期版本或 Opera 中不支持 <textarea>标签的 maxlength 属性。

from HTML maxlength Attribute w3school. com

For IE8 or earlier versions you have to use the following

//only call this function in IE
function maxLengthLimit($textarea){
var maxlength = parseInt($textarea.attr("maxlength"));
//in IE7,maxlength attribute can't be got,I don't know why...
if($.browser.version=="7.0"){
maxlength = parseInt($textarea.attr("length"));
}
$textarea.bind("keyup blur",function(){
if(this.value.length>maxlength){
this.value=this.value.substr(0,maxlength);
}
});
}

附言。

所有主流浏览器都支持 <input>标记的 maxlength 属性。

HTML maxlength Attribute w3school. com

您可以使用 jQuery 使其简单明了

JSFiddle 演示

<textarea id="ta" max="10"></textarea>


<script>
$("#ta").keypress(function(e){


var k = e.which==0 ? e.keyCode : e.which;
//alert(k);
if(k==8 || k==37 || k==39 || k==46) return true;


var text      = $(this).val();
var maxlength = $(this).attr("max");


if(text.length >= maxlength) {
return false;
}
return true;
});
</script>

FirefoxGoogle ChromeOpera中进行测试

2022年最新情况

You can set the HTML attribute for "maxlength" with the property maxLength (note the uppercase L). You might end up on this page if you were trying to use maxlength (all lowercase) and it wasn't working.

textareaElement1.maxLength = 50;
textareaElement2.maxLength = 150;
textareaElement3.maxLength = 250;

如果你想以编程的方式处理所有现有的文本区域,你可以迭代一个 getElementsByTagName结果:

const textAreas = document.getElementsByTagName('textarea');
for (const element of textAreas) {
element.maxLength = 150;
}