I want to set maximum length to the textarea. I am using following code for the same,but it is not working,
please use jquery for reference
<script type="text/javascript">
$().ready(function(){
$("#textareaId").attr('maxlength','20');
});
</script>
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
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>
Maxlength attribute for textarea works in Chrome.
There's no maxlength
attribute defined for textarea
. You need to implement this using javascript.
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));
});
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));
}
});