user2377971
user2377971

Reputation: 1452

How to make primefaces inputTextArea fit to text?

i'm trying to make <p:inputTextArea/> looks better, now when page is loaded i can see: enter image description here

and when i click that TextArea : enter image description here

here is the code:
<p:inputTextarea rows="6" value="#{bean.object.value}"style="width: 100%;" />

How can i make that area would adjust its size to text ? rows="6" is working for a little data but it looks terrible when more chars are written

Upvotes: 4

Views: 16399

Answers (4)

Rodrigo
Rodrigo

Reputation: 385

Self explanatory code:

<p:inputTextarea
    rows="#{myBean.numberOfLines(myBean.myClass.theString, 70)}"
    cols="70"
    value="#{myBean.myClass.theString}"
    autoResize="true" />

public int numberOfLines(String string, int cols) {
        int rvalue = 0;
        for (String strTmp : string.split("\n")) {
            rvalue ++;
            rvalue += strTmp.length() >= cols ? strTmp.length() / cols : 0;
        }
        return rvalue;
    }

Edit: This will not work for every case, because of the size of the text, but for me, it's enough.

Upvotes: 3

Brother
Brother

Reputation: 2210

I had the same problem today. Counting cols only works if the user don't type line-breaks. After looking for a best solution I solved my case this way:

<p:inputTextarea
        value="#{comment.body}" 
        styleClass="no-border" readonly="true"
        style="width: 80%;height: 100%;"
        rows="#{myController.countChar(comment.body)+2}" />

And in MyController:

public int countChar(String text) {
    return StringUtils.countMatches(text, "\n");
}

By default, the inputTextarea has the attribute "autoResize=true".So, if you need to edit, after you type something, the component will fit your text.

Upvotes: 0

JavaG
JavaG

Reputation: 21

I've found that the best way is to dynamically set the rows attribute based on the existing bean string length. You'll need to set columns which is worth it to accomplish the goal.

rows="#{2 + bean.string.length()/100}" cols="100"

Upvotes: 2

Hatem Alimam
Hatem Alimam

Reputation: 10048

I'd solve my problem with this plugin flexibleArea.js, but if you download it it won't fix the first time you focus on the textArea, so I had to tweak it a bit.

I have added to the bind a new event which is focus.

$textarea.bind('keyup change cut paste focus'

Now to get this working, download my tweak flexibleArea.js, include it in your xhtml, then in the document ready.

$(function() {         
   $('.ui-inputtextarea').flexible();    
});

And Here's a live demo on Primefaces TextArea flexible, and on github.

Hope this Helps.

Upvotes: 8

Related Questions