I would like to have some functionality by which if I write
<textarea maxlength="50"></textarea>
<textarea maxlength="150"></textarea>
<textarea maxlength="250"></textarea>
it will automatically impose the maxlength on the textArea. If possible please do not provide the solution in jQuery.
Note: This can be done if I do something like this:
<textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50">
function imposeMaxLength(Event, Object, MaxLen)
{
return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
}
Copied from What is the best way to emulate an HTML input “maxlength” attribute on an HTML textarea?
But the point is I don't want to write onKeyPress and onKeyUp every time I declare a textArea.
This is some tweaked code I've just been using on my site. It is improved to display the number of remaining characters to the user.
(Sorry again to OP who requested no jQuery. But seriously, who doesn't use jQuery these days?)
Has NOT been tested with international multi-byte characters, so I'm not sure how it works with those exactly.
This solution avoids the issue in IE where the last character is removed when a character in the middle of the text is added. It also works fine with other browsers.
My form validation then deals with any issues where the user may have pasted (only seems to be a problem in IE) text exceeding the maximum length of the textarea.
This is much easier:
You can use jQuery to make it easy and clear
JSFiddle DEMO
It is tested in
Firefox
,Google Chrome
andOpera
HTML5 adds a
maxlength
attribute to thetextarea
element, like so:This is currently supported in Chrome 13, FF 5, and Safari 5. Not surprisingly, this is not supported in IE 9. (Tested on Win 7)
Small problem with code above is that val() does not trigger change() event, so if you using backbone.js (or another frameworks for model binding), model won't be updated.
I'm posting the solution worked great for me.