在 Html Textarea 中设置 maxlength

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4459610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:44:18  来源:igfitidea点击:

Set maxlength in Html Textarea

htmlinputtextarea

提问by Hitesh Prajapati

How can I set the maxlengthin a textarea? And why maxlengthis not working properly in textarea?

我怎样才能maxlength在 a 中设置textarea?为什么maxlength在 中不能正常工作textarea

回答by aqingsao

Before HTML5, we have an easy but workable way: Firstly set an maxlength attribute in the textarea element:

在 HTML5 之前,我们有一个简单但可行的方法:首先在 textarea 元素中设置一个 maxlength 属性:

<textarea maxlength='250' name=''></textarea>  

Then use JavaScript to limit user input:

然后使用 JavaScript 来限制用户输入:

$(function() {  
    $("textarea[maxlength]").bind('input propertychange', function() {  
        var maxLength = $(this).attr('maxlength');  
        if ($(this).val().length > maxLength) {  
            $(this).val($(this).val().substring(0, maxLength));  
        }  
    })  
});

Make sure the bind both "input" and "propertychange" events to make it work on various browsers such as Firefox/Safari and IE.

确保绑定“ input”和“ propertychange”事件以使其在各种浏览器上工作,例如Firefox/Safari和IE。

回答by Oded

If you are using HTML 5, you need to specify that in your DOCTYPEdeclaration.

如果您使用 HTML 5,则需要在DOCTYPE声明中指定。

For a valid HTML 5 document, it should start with:

对于有效的 HTML 5 文档,它应该以以下开头:

<!DOCTYPE html>


Before HTML 5, the textareaelement did not have a maxlengthattribute.

在 HTML 5 之前,textarea元素没有maxlength属性。

You can see this in the DTD/spec:

您可以在DTD/spec 中看到这一点:

<!ELEMENT TEXTAREA - - (#PCDATA)       -- multi-line text field -->
<!ATTLIST TEXTAREA
  %attrs;                              -- %coreattrs, %i18n, %events --
  name        CDATA          #IMPLIED
  rows        NUMBER         #REQUIRED
  cols        NUMBER         #REQUIRED
  disabled    (disabled)     #IMPLIED  -- unavailable in this context --
  readonly    (readonly)     #IMPLIED
  tabindex    NUMBER         #IMPLIED  -- position in tabbing order --
  accesskey   %Character;    #IMPLIED  -- accessibility key character --
  onfocus     %Script;       #IMPLIED  -- the element got the focus --
  onblur      %Script;       #IMPLIED  -- the element lost the focus --
  onselect    %Script;       #IMPLIED  -- some text was selected --
  onchange    %Script;       #IMPLIED  -- the element value was changed --
  %reserved;                           -- reserved for possible future use --
  >

In order to limit the number of characters typed into a textarea, you will need to use javascript with the onChangeevent. You can then count the number of characters and disallow further typing.

为了限制输入到 a 中的字符数textarea,您需要在onChange事件中使用 javascript 。然后,您可以计算字符数并禁止进一步键入。

Hereis an in-depth discussion on text input and how to use server and client side scripting to limit the size.

是关于文本输入以及如何使用服务器和客户端脚本来限制大小的深入讨论。

Hereis another sample.

是另一个示例。

回答by Dss

simple way to do maxlength for textarea in html4 is:

在 html4 中为 textarea 做 maxlength 的简单方法是:

<textarea cols="60" rows="5" onkeypress="if (this.value.length > 100) { return false; }"></textarea>

Change the "100" to however many characters you want

将“100”更改为您想要的任意字符数

回答by Coxy

As I said in a comment to aqingsao's answer, it doesn't quite work when the textareahas newline characters, at least on Windows.

正如我在对 aqingsao 的回答的评论中所说的那样,当textarea有换行符时,它不太适用,至少在 Windows 上是这样。

I've change his answer slightly thus:

我稍微改变了他的答案:

$(function() {
    $("textarea[maxlength]").bind('input propertychange', function() {
        var maxLength = $(this).attr('maxlength');
        //I'm guessing JavaScript is treating a newline as one character rather than two so when I try to insert a "max length" string into the database I get an error.
        //Detect how many newlines are in the textarea, then be sure to count them twice as part of the length of the input.
        var newlines = ($(this).val().match(/\n/g) || []).length
        if ($(this).val().length + newlines > maxLength) {
            $(this).val($(this).val().substring(0, maxLength - newlines));
        }
    })
});

Now when I try to paste a lot of data in with newlines, I get exactly the right number of characters.

现在,当我尝试使用换行符粘贴大量数据时,我得到了正确数量的字符。

回答by Sony Aja

$(function(){  
  $("#id").keypress(function() {  
    var maxlen = 100;
    if ($(this).val().length > maxlen) {  
      return false;
    }  
  })
});  

回答by Maxtor

<p>
   <textarea id="msgc" onkeyup="cnt(event)" rows="1" cols="1"></textarea> 
</p> 
<p id="valmess2" style="color:red" ></p>

function cnt(event)
{ 
 document.getElementById("valmess2").innerHTML=""; // init and clear if b < max     
allowed character 

 a = document.getElementById("msgc").value; 
 b = a.length; 
 if (b > 400)
  { 
   document.getElementById("valmess2").innerHTML="the max length of 400 characters is 
reached, you typed in  " + b + "characters"; 
  } 
}

maxlength is only valid for HTML5. For HTML/XHTML you have to use JavaScript and/or PHP. With PHP you can use strlen for example.This example indicates only the max length, it's NOT blocking the input.

maxlength 仅对 HTML5 有效。对于 HTML/XHTML,您必须使用 JavaScript 和/或 PHP。例如,您可以使用 PHP 使用 strlen。此示例仅指示最大长度,它不会阻止输入。

回答by smnbbrv

try this

尝试这个

$(function(){
  $("textarea[maxlength]")
    .keydown(function(event){
       return !$(this).attr("maxlength") || this.value.length < $(this).attr("maxlength") || event.keyCode == 8 || event.keyCode == 46;
    })
    .keyup(function(event){
      var limit = $(this).attr("maxlength");

      if (!limit) return;

      if (this.value.length <= limit) return true;
      else {
        this.value = this.value.substr(0,limit);
        return false;
      }    
    });
});

For me works really perfect without jumping/showing additional characters; works exactly like maxlength on input

对我来说,无需跳转/显示其他字符即可完美运行;与输入的 maxlength 完全一样

回答by acme

Before HTML5 it's only possible to check this with JavaScript or by a server-side verification (better, because JavaScript obviously only works with JavaScript enabled...). There is no native max-length attribute for textareas.

在 HTML5 之前,只能使用 JavaScript 或通过服务器端验证来检查这一点(更好,因为 JavaScript 显然只能在启用 JavaScript 的情况下工作......)。文本区域没有本机最大长度属性。

Since HTML5 it's a valid attribut, so defining your doctype as HTML5 may help. I don't know if all browsers support this attribute, though:

由于 HTML5 这是一个有效的属性,因此将您的文档类型定义为 HTML5 可能会有所帮助。不过,我不知道是否所有浏览器都支持此属性:

<!DOCTYPE html>

回答by Muhammad Sanaullah khan

resize:none; This property fix your text area and bound it. you use this css property id your textarea.gave text area an id and on the behalf of that id you can use this css property.

调整大小:无;此属性修复您的文本区域并绑定它。你使用这个 css 属性 id 你的 textarea.gave 文本区域一个 id 并且代表那个 id 你可以使用这个 css 属性。