简体   繁体   English

如何使用 JavaScript 在 HTML 中的 textArea 上施加 maxlength

[英]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.它会自动将最大长度强加在 textArea 上。 If possible please do not provide the solution in jQuery.如果可能,请不要在 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?复制自在 HTML 文本区域上模拟 HTML 输入“maxlength”属性的最佳方法是什么?

But the point is I don't want to write onKeyPress and onKeyUp every time I declare a textArea.但关键是我不想在每次声明 textArea 时都写 onKeyPress 和 onKeyUp。

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;
    } 
  };

}

I know you want to avoid jQuery, but as the solution requires JavaScript, this solution (using jQuery 1.4) is the most consise and robust.我知道您想避免使用 jQuery,但由于该解决方案需要 JavaScript,因此该解决方案(使用 jQuery 1.4)是最简洁和健壮的。

Inspired by, but an improvement over Dana Woodman's answer:受到 Dana Woodman 回答的启发,但有所改进:

Changes from that answer are: Simplified and more generic, using jQuery.live and also not setting val if length is OK (leads to working arrow-keys in IE, and noticable speedup in IE):该答案的变化是:简化且更通用,使用 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编辑: jQuery 1.7+的更新版本,使用on而不是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));
    }
});

Update Use Eirik's solution using .live() instead as it is a bit more robust.更新使用 Eirik 的解决方案,使用.live()代替,因为它更健壮。


Even though you wanted a solution that wasn't using jQuery, I thought I'd add one in for anyone finding this page via Google and looking for a jQuery-esque solution:即使您想要一个不使用 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));
        });

    });
});

Hope that is useful to you Googlers out there...希望这对您的 Google 员工有用...

HTML5 adds a maxlength attribute to the textarea element, like so: 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) Chrome 13、FF 5 和 Safari 5 目前支持此功能。毫无疑问,IE 9 不支持此功能。(在 Win 7 上测试)

This solution avoids the issue in IE where the last character is removed when a character in the middle of the text is added.此解决方案避免了在 IE 中添加文本中间的字符时删除最后一个字符的问题。 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" );
});

My form validation then deals with any issues where the user may have pasted (only seems to be a problem in IE) text exceeding the maximum length of the textarea.然后,我的表单验证会处理用户可能粘贴的任何问题(仅在 IE 中似乎是一个问题)超过文本区域最大长度的文本。

This is some tweaked code I've just been using on my site.这是我刚刚在我的网站上使用的一些经过调整的代码。 It is improved to display the number of remaining characters to the user.改进了向用户显示剩余字符数。

(Sorry again to OP who requested no jQuery. But seriously, who doesn't use jQuery these days?) (再次向不要求 jQuery 的 OP 道歉。但是说真的,这些天谁不使用 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.尚未使用国际多字节字符进行测试,因此我不确定它如何与这些字符一起使用。

Also add the following event to deal with pasting into the textarea:还要添加以下事件来处理粘贴到 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;
  }
}

...

The maxlength attribute is supported in Internet Explorer 10, Firefox, Chrome, and Safari. Internet Explorer 10、Firefox、Chrome 和 Safari 支持 maxlength 属性。

Note: The maxlength attribute of the <textarea> tag is not supported in Internet Explorer 9 and earlier versions, or in Opera.注意: <textarea>标签的 maxlength 属性在 Internet Explorer 9 及更早版本或 Opera 中不受支持。

from HTML maxlength Attribute w3schools.com来自HTML maxlength 属性 w3schools.com

For IE8 or earlier versions you have to use the following对于 IE8 或更早版本,您必须使用以下内容

//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);
        }
    });
}

PS附言

The maxlength attribute of the <input> tag is supported in all major browsers.所有主流浏览器都支持<input>标签的 maxlength 属性。

from HTML maxlength Attribute w3schools.com来自HTML maxlength 属性 w3schools.com

You can use jQuery to make it easy and clear你可以使用 jQuery 让它变得简单明了

JSFiddle DEMO 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>

It is tested in Firefox , Google Chrome and Opera已在FirefoxGoogle ChromeOpera中测试

Better Solution compared to trimming the value of the textarea.与修剪 textarea 的值相比,更好的解决方案。

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

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

I implemented maxlength behaviour on textarea recently, and run into problem described in this question: Chrome counts characters wrong in textarea with maxlength attribute .我最近在textarea上实现了maxlength行为,并遇到了这个问题中描述的问题: Chrome counts characters wrong in textarea with maxlength attribute

So all implementations listed here will work little buggy.所以这里列出的所有实现都会有一些小错误。 To solve this issue I add .replace(/(\r\n|\n|\r)/g, "11") before .length .为了解决这个问题,我在.length之前添加了.replace(/(\r\n|\n|\r)/g, "11") And kept it in mind when cuting string.并在剪线时牢记这一点。

I ended with something like this:我以这样的方式结束:

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)));
}

Don't sure if it solves problem completely, but it works for me for now.不确定它是否完全解决了问题,但它现在对我有用。

Try this jQuery which works in IE9, FF, Chrome and provides a countdown to users:试试这个适用于 IE9、FF、Chrome 并为用户提供倒计时的 jQuery:

$("#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>

Try to use this code example:尝试使用此代码示例:

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

2022 Update 2022 更新

You can set the HTML attribute for "maxlength" with the property maxLength (note the uppercase L).您可以使用属性maxLength (注意大写 L)为“maxlength”设置 HTML 属性。 You might end up on this page if you were trying to use maxlength (all lowercase) and it wasn't working.如果您尝试使用maxlength (全部小写)并且它不起作用,您可能最终会出现在此页面上。

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

If you wanted to programmatically do it to all existing textareas, you could just iterate over a getElementsByTagName result:如果您想以编程方式对所有现有文本区域执行此操作,则可以迭代getElementsByTagName结果:

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

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.上面代码的小问题是 val() 不会触发 change() 事件,所以如果您使用backbone.js(或其他模型绑定框架),模型将不会更新。

I'm posting the solution worked great for me.我发布的解决方案对我很有用。

$(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 onKeyPress="return ( this.value.length < 1000 );"></textarea>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM