How to impose maxlength on textArea using JQuery

How to impose maxlength on textArea using JQuery


$(function() {

// Get all textareas that have a “maxlength” property.
$(‘textarea[maxlength]‘).each(function() {

    // Store the jQuery object to be more efficient...
    var $textarea = $(this);

    // Store the maxlength and value of the field.
    var maxlength = $textarea.attr('maxlength');
    var val = $textarea.val();

    // Trim the field if it has content over the maxlength.
    $textarea.val(val.slice(0, maxlength));

    // Bind the trimming behavior to the "keyup" event.
    $textarea.bind('keyup', function() {
        $textarea.val($textarea.val.slice(0, maxlength));
    });

});

});

Best solution

[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;
}
}
}

[/javascript]