Text Area maxlength not working
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));
});