Sabry Shawally
Sabry Shawally

Reputation: 603

Attach Jquery events to JSF data tables

Since we can apply JQuery to any JSF rendered components, as in the following question

JSF to JQuery Component Integration

After having tried that, it did work I can successfully integrate JQuery into JSF, but the problem is that whenever I re-render the h:dataTable for instance, JQuery stops working, -I'm using RichFaces and the a4j, by the way-.

For example, I have a data table as follows

<h:dataTable id="someDataTable" value="#{backingBean.someDataModel}" var="item" styleClass="table">
   <h:column>
      <h:outputText value="#{item.text}"/>
   </h:column>
</h:dataTable>

and I have a button that when clicked re-renders the dataTable, and repopulate it with new data.

<a4j:commandButton value="Click" reRender="someDataTable"/>

and not to forget I have this script in the page

<script>
  jQuery.noConflict();
   jQuery(document).ready(function () {
      jQuery('.table').dataTable({
    "bSort": false}); 
    });
</script>

Now when the page is first loaded, sorting works fine, but whenever I click the button to re-render the table, the table is successfully populated with the new data from the backing bean, but the sorting doesn't work anymore.

From what I guess, I think this might has something to do with the

jQuery(document).ready()

which applies the

jQuery.('.table').dataTable(); 

only when the document is ready, so I was wondering if there's some events in jQuery that I can attach to the dataTable re-render event, as I'm no guru at JQuery or JS.

Upvotes: 0

Views: 1277

Answers (1)

BalusC
BalusC

Reputation: 1109635

Just re-execute the script when the ajax request has completed.

First refactor your script into a reuseable function.

<script>
    jQuery.noConflict();
    jQuery(document).ready(function() {
        initDataTable();
    });
    function initDataTable() {
        jQuery('.table').dataTable({
            "bSort": false
        }); 
    }
</script>

Then invoke the same function in oncomplete of <a4j:commandButton>.

<a4j:commandButton ... oncomplete="initDataTable()" />

Upvotes: 1

Related Questions