Friday, 27 February 2015

Setting maxlength to a textarea

The maxlength attribute is new for the <textarea> tag in HTML5.

But what if  you are not using html5 or what if your browser doesn't support this attribute.

You might have faced this issue where you being not able to set maxlength property to a textarea.

So here is the trick using the power of Jquery  :P.

var maxLength = 50; //Set the length here
$(document).ready(function(){
setMaxLenTexrArea();
});
function setMaxLenTexrArea() {
    $("textarea").each(function () {
        $(this).on('change keydown keyup keypress paste blur', function () {
            restrictLength($(this).prop('id'));
        });
    });
}
function restrictLength(ta) {
 
    var txtVal = $("#" + ta).val();
    if (txtVal.length > maxLength) {
        txtVal = txtVal.substring(0, maxLength);
        $("#" + ta).val(txtVal);
    }
}
Explanation: 

  • maxLength variable will hold the length.
  • On document load we will be calling setMaxLenTexrArea() method.
  • We will be restricting the user to enter (type/paste) only allowed number of characters by checking the existing values length in the textarea and not allowing further if it has reached thr limit.
Hope it helped you :)