views:

50

answers:

1

I am creating a Comment-Reply system, similar to stackoverflow and I wonder how to implement it using JSF + jQuery. I have a dataTable, each row have a link and a textBox, and once I click a link, only the textbox on that same row appear, and put focus on that textbox.

<h:form id="userComment">
    <p:dataTable value="bean.comments">
         <p:column>
              <!-- link that if u click on it, the textbox below appear -->
              <h:inputTextarea id="reply" />      
         </p:column>
    </p:dataTable>
</h:form>

My main obstacle is that, normal jQuery user would do this: let assume the link id is foo then

$('#foo').click(function(){
    //Make the box with id `reply` appear and put focus on it
});

But since each row has a textbox call reply, there will be prependId before reply and foo like this userComment:1:foo or userComment:1:reply. Therefore $('#foo') and $('#reply') would not work

+2  A: 

Use this and replace the smart way.

E.g.

<h:form>
    <p:dataTable value="#{bean.comments}" var="comment">
        <p:column>
            <h:outputText value="#{comment.text}" />
            <h:outputLink id="add" value="#" onclick="showReply(this)">Add reply</h:outputLink>
            <h:inputTextarea id="reply" value="#{comment.reply}" style="display:none;" />
        </p:column>
    </p:dataTable>
</h:form>

with

<script>
    function showReply(link) {
        jQuery(PrimeFaces.escapeClientId(link.id.replace(/add$/, 'reply'))).slideDown(function() {
            jQuery(this).focus();
        });
    }
</script>

The string.replace(/add$/, 'reply') will replace foo:1:add to foo:1:reply and the PrimeFaces-supplied function PrimeFaces.escapeClientId() will escape it into a valid jQuery ID selector. Finally, you can do the focus in the callback.

BalusC
it is just beautiful. Thank you. Now there is one thing that I find interesting, if I have the exact JSF like u have with the `h:form` outside, then I get this warning `The form component needs to have a UIForm in its ancestry. Suggestion: enclose the necessary components within <h:form>`. So i have to have a second `h:form`, wrap inside `h:inputTextarea` and that warning go away. Weird !!!
Harry Pham
You're welcome.
BalusC