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 :)

Comments

Popular posts from this blog

SharePoint Online (O365) OAuth Authentication | Authorizing REST API calls against SharePoint Online Site | Get Access token from SharePoint Online | Set up OAuth for SharePoint Online Office 365

SharePoint 2013 REST API Reference

Simple Risk Assessment Matrix table with resultant risk calculation

Kendo UI (Core JavaScript) grid Server Paging, Server Sorting and Server Filtering with Dynamic SQL queries

Sharepoint- Using an Image From formatmap32x32.png in a Ribbon Control