How to impose maxlength on textArea in HTML using JavaScript
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA');
for(var i = 0, l = txts.length; i < l; i++) {
if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) {
var func = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if(this.value.length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
};
}
Text Area maxlength not working
There's no maxlength
attribute defined for textarea
. You need to implement this using javascript.
Jquery help to enforce maxlength on textarea?
This is the best solution!
Put this into your script tag in HTML code
$("textarea[maxlength]").on("propertychange input", function() {
if (this.value.length > this.maxlength) {
this.value = this.value.substring(0, this.maxlength);
}
});
and now use <textarea maxlength="{your limit}"></textarea>
for {your limit}
chars limit.
textarea character limit
Generate functions that will either truncate the value or prevent the Event under your conditions, and then add them as several different listeners for all the events you're interested in.
function snip(len) {
return function (e) {e.target.value = e.target.value.slice(0, len);};
}
function prevent(len) {
return function () {
if (e.target.value.length >= len) {
e.preventDefault();
return false;
}
};
}
var len = 5; // choose your length however you want
var textarea = document.getElementById('texta'), // get the node
trunc = snip(len),
prev1 = prevent(len),
prev2 = prevent(len - 1);
textarea.addEventListener('change' , trunc, true);
textarea.addEventListener('input' , trunc, true);
textarea.addEventListener('keydown' , prev2, true);
textarea.addEventListener('keypress', prev2, true);
textarea.addEventListener('keyup' , prev1, true);
textarea.addEventListener('paste' , trunc, true);
The events may need to be attached differently in IE
DEMO
Related Topics
How to Detect Keypresses in JavaScript
(Change) VS (Ngmodelchange) in Angular
How to Get the Values of Data Attributes in JavaScript Code
How to Do a Jquery Callback After Form Submit
How to Add an "Add to Favorites" Button or Link on My Website
How to Pick Element Inside Iframe Using Document.Getelementbyid
How to Run an .Exe or .Bat File on 'Onclick' in Html
Can JavaScript Read the Source of Any Web Page
Do You Need Text/JavaScript Specified in Your ≪Script≫ Tags
Method to Show Native Datepicker in Chrome
What Is Offsetheight, Clientheight, Scrollheight
How to Prevent Iframe from Redirecting Top-Level Window
Does Html5/Canvas Support Double Buffering
How to Clear an HTML File Input With JavaScript
How Does the Paste Image from Clipboard Functionality Work in Gmail and Google Chrome 12+