How to Impose Maxlength on Textarea in HTML Using JavaScript

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



Leave a reply



Submit