Search code examples
javascripthtmlstruts2textareastruts-tags

How to make a readonly <s:textarea /> fit to its content


I have a textarea in my form :

<s:textarea key = "appInfo.collection" 
       required = "true" 
       readonly = "true"
       cssClass = "form-control" 
           rows = "8"/>

and few more textarea fields. I want to make these textareas fit their content in readonly mode.

Since I have specified rows=8 it sometimes shows a blank area if content fills only 2 rows, or shows a scrollbar if content is more than 8 rows.

How can I give these textareas the right size based on their content, with no scrollbars ?


Solution

  • You can use the answer linked in my comment.

    Regarding your comment

    My text areas are in read mode and I do not have keyup function available for them

    You don't need any keyup handler: since it is readonly, do it once, after the page has loaded:

    <s:textarea id = "myTextarea"
               key = "appInfo.collection" 
          required = "true" 
          readonly = "true"
          cssClass = "form-control" 
              rows = "8"/>
    
    function autoheight(a) {
        if (!$(a).prop('scrollTop')) {
            do {
                var b = $(a).prop('scrollHeight');
                var h = $(a).height();
                $(a).height(h - 5);
            }
            while (b && (b != $(a).prop('scrollHeight')));
        };
        $(a).height($(a).prop('scrollHeight') + 20);
    }
    
    $(function(){ 
        // call the function in document.ready 
        autoheight($("#myTextarea"));
    });