开发者

Text Area maxlength not working

开发者 https://www.devze.com 2023-01-12 05:09 出处:网络
I want to set maximum length t开发者_高级运维o the textarea. I am using following code for the same,but it is not working,

I want to set maximum length t开发者_高级运维o the textarea. I am using following code for the same,but it is not working,

<textarea name="txtDescription" cols=10 rows=3 maxlength=50></textarea>

But it is not working,it takes characters beyond 50.


There's no maxlength attribute defined for textarea. You need to implement this using javascript.


Yup maxlength does not work in textarea. But you can use jQuery something like this:

var $limitNum = 500;
$('textarea[name="textarea_name"]').keydown(function() {
    var $this = $(this);

    if ($this.val().length > $limitNum) {
        $this.val($this.val().substring(0, $limitNum));
    }
});


I tried maxlength in textarea, but does not count the characters correctly(also counts the EOLs). I use max_length attribute instead of normal maxlength.

HTML:

<textarea name="whatever" max_length="100"></textarea>

JS:

$('textarea').keyup(function(){
  var maxlength = parseInt($(this).attr('max_length')),
      text = $(this).val(),
      eol = text.match(/(\r\n|\n|\r)/g),
      count_eol = $.isArray(eol) ? eol.length : 0,//error if eol is null
      count_chars = text.length - count_eol;
  if (maxlength && count_chars > maxlength)
    $(this).val(text.substring(0, maxlength + count_eol));
});


When the answer of Darin Dimitrov was posted back in 2010, the maxlength attribute wasn't implemented apparently.

Right know, in 2018, it is.

Sources

  • caniuse
  • MDN

Example

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <label for="without">Without maxlength</label>
  <textarea id="without" class="form-control"></textarea>
  <br>
  <label for="with">With maxlength="10"</label>
  <textarea id="with" maxlength="10" class="form-control"></textarea>
</div>


Answers above are correct for earlier version of IE 10.

If you are having problem with maxlength attribure, my recommendation is check your browser version first. The maxlength attribute is new for the tag in HTML5. It should be just fine on IE 10+ or Chrome.


Maxlength attribute for textarea works in Chrome.


you can use

<textarea name="testString" onkeypress="if (this.value.length >= 250) { return false; }"id="" cols="30" rows="10" maxlength="250"></textarea>


You need to put it into the HTML tag like this, make sure you have airquotes "".

<textarea maxlength="5"></textarea>


This works for Ruby on Rails :

:maxlength => "10"

code example:

<%= text_area 'order', 'special_instructions_display', :size => "85x7", :maxlength => "10"  %>


please use jquery for reference

<script type="text/javascript">  
$().ready(function(){   

     $("#textareaId").attr('maxlength','20');   

 });
</script>  
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号