I want to set maximum length to 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.
I want to set maximum length to 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.
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));
}
});
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));
});
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>
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.
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>
please use jquery for reference
<script type="text/javascript">
$().ready(function(){
$("#textareaId").attr('maxlength','20');
});
</script>