Search code examples
ajaxjsffaceletsmanaged-bean

How to use ajax update content but without submit button


I have a jsf code like this. When user finish to input name and comment and press 'Enter', the content can show in 'Content........' this part.

<h:form id="all_comments">
    Content........
</h:form>
<h:form id="submit_comment">
    <h:inputText id="name_box" value="#{ManagedBean.user}"/>
    <h:inputText id="content_box" value="#{ManagedBean.comment}" />
</h:form>

I want to use ajax finish it, and I try like this:

<h:form id="all_comments">
    Content........
</h:form>
<h:form id="submit_comment">
    <h:inputText id="name_box" value="#{ManagedBean.user}"/>
    <h:inputText id="content_box" value="#{ManagedBean.content}">
        <f:ajax event="keydown"
                listener="#{ManagedBean.addComment}"
                execute="comment_name_box comment_content_box"
                rendered=":all_comments" />
    </h:inputText>
</h:form>

But I failed, can I achieve that when user press 'Enter', data will be processed by ManagedBean, then using ajax update the page.


Solution

  • You've got some points missing:

    1. You need to send an AJAX call only when enter key was pressed, so you need to bind <h:inputText> tag's onkeydown attribute with JavaScript code for that;
    2. <f:ajax> attribute is render, not rendered;
    3. submit_comment form should be rerendered as well, so that new data will be presented to the user, and the placeholders have to be refreshed in AJAX listener as well.

    Here is the solution when you want to submit the second form on that event:

    <h:form id="all_comments">
        Content........
    </h:form>
    <h:form id="submit_comment">
        <h:inputText id="name_box" value="#{managedBean.user}"/>
        <h:inputText id="content_box" value="#{managedBean.content}"
                     onkeydown="return (event.keyCode == 13);">
            <f:ajax event="keydown"
                    listener="#{managedBean.addComment}"
                    execute="@form"
                    render="@form :all_comments" />
        </h:inputText>
    </h:form>
    

    with

    public void addComment(AjaxBehaviorEvent abe) {
        comments.add(new Comment(user, content));
        user = "";
        content = "";
    }