简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM