membersound
membersound

Reputation: 86925

get value of inputText on the fly without backing bean?

can I get the value of a inputTextare on the fly without backing bean?

<p:dialog>
<p:inputTextarea rows="5" cols="30" value="#{_var.note}" />
<h:outputText id="remaining" value="#{util.getCharactersRemaining("varibale of textarea", 160)} characters left" />



public class UtilFacade {
    public int getCharactersRemaining(String value, int maxLength) {
        log.info("length: " + value.length());
        return (maxLength - value.length());
    }
}

In order to display the remaining chars in the dialog, I have to feed the method with current value in Textarea without saving the value to a backing bean! How can i get this value?

Upvotes: 1

Views: 468

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85799

You can do this with a JavaScript method (no need to go to server). Here is a sample:

<script type="text/javascript">
    function getRemainingChars(textArea, maxLength) {
        var actualText = textArea.value;
        if (actualText.length > maxLength) {
            textArea.value = actualText.substring(0, maxLength);
        }
        var remainingChars = (maxLength > actualText.length) ? maxLength - actualText.length : 0;
        document.getElementById("frmMyPage:txtRemainingChars").value = remainingChars;
    }
</script>
<h:form id="frmMyPage">
<h:inputTextArea id="txtTextArea" cols="50" rows="10" onkeyup="getRemainingChars(this, 500);" />
<br />
<h:outputText id="txtRemainingChars" />
</h:form>

You can get more details about keydown, keypress and keyup javascript functions here (in this case I preffer to validate the text on the keyup event). Also you can modify the JavaScript function and send the id of your component instead of sending the whole component (this will make the JS available for inputText component and similars).

Upvotes: 4

Related Questions