JSF / PrimeFaces: Navigate from one tab to another

Ranjith picture Ranjith · Dec 3, 2013 · Viewed 14.9k times · Source

Using Primefaces tab view (<p:tabView>), how to navigate from one tab to another tab?

For example:

<p:tabView id="tabPanel">
  <p:tab id="tab1">
       <p>Tab 1</p>
       <a href="#">Go to tab2</a2>
  </p:tab>
   <p:tab id="tab2">
       <p>Tab 2</p>
  </p:tab>   
</p:tabView>

Answer

erencan picture erencan · Dec 3, 2013

You can use client side scripting api of PrimeFaces. Define a widgetVar attribute in tabView. Then use select(index) client side api.

<p:tabView id="tabPanel" widgetVar="tabPanelWidget">
  <p:tab id="tab1">
       <p>Tab 1</p>
       <a href="#" onclick="changeTab(1);">Go to Tab2</a2>
  </p:tab>
   <p:tab id="tab2">
       <p>Tab 2</p>
  </p:tab>   
</p:tabView>

Be carefull about the parameter to JS function. the index of tab , which is zero based, is passed to Javascript.

here is client side code

function changeTab(index)
{
    tabPanelWidget.select(index);
}

tabView with Dynamic Content

Furthermore, if you have dynamic content you can simulate the client side api as user click the tab.

I go deep into source code of the component. A tabview component consist of a div and unordered list items which include a <a> tags to click. Then i select that <a> tags from the page and clicked with jquery.

See my jquery code:

function changeTab(tabId)
    {
       $('#formId\\:tabPanel ul li a[href="#form:tabPanel:"+tabId+"]').click();
}

Here is the details of selectors.

#formId\:tabPanel : formId is the id of the page. If prependId="false" is used this part can be skipped. \\ is escape for : and tabPanel is the id of the tabview.

ul li : is unordered list items which represents tabs.

a[href="#form:tabPanel:"+tabId+"]' : <a> tag whose href attribure is equals to tabId.

Furthermore, i inspect the source code from PrimeFaces showcase. It may be have some differences in your codes.