Search code examples
javascriptjsfprimefacestabmenu

Use p:tabMenu with JavaScript


I am currently using an h:selectOneRadio to display three filtering options. When a radio button is clicked, a JavaScript function is called to iterate through a number of items below to change the display CSS property corresponding to the filter option selected. This works very well, and does not have a round trip to the server (no POST or AJAX).

This will give you an idea of the current implementation.

<script type="text/javascript">
function criteria_filterClick(radio)
{
    radio.value == 'selected' ? criteria_showOnlySelected() :
        radio.value == 'significant' ? criteria_showFirstOrSelected() :
        criteria_showAll();
}
</script>

<h:selectOneRadio id="filter" onclick="criteria_filterClick(this); return true;"
        value="#{searchBean.criterionFilter}">
    <f:selectItem itemValue="selected" itemLabel="Selected"/>
    <f:selectItem itemValue="significant" itemLabel="Basic"/>
    <f:selectItem itemValue="all" itemLabel="All"/>
</h:selectOneRadio>

However, I feel like having tabs would be a better UI metaphor than radio buttons. I'm looking at PrimeFaces' p:tabMenu component with p:menuitems inside it. However, the documentation for those two components doesn't appear to have any support for straight JavaScript.

Here's what I've got started, but I don't know where to go from there:

<p:tabMenu activeIndex="#{searchBean.criterionFilter == 'selected' ? 0 : (searchBean.criterionFilter == 'significant' ? 1 : 2)}">
    <p:menuitem value="Selected"/>
    <p:menuitem value="Basic"/>
    <p:menuitem value="All"/>
</p:tabMenu>

At this point, there is no functionality (it doesn't even change tab highlighting when you click on one of them). Is there a way to add JavaScript to p:tabMenu? Or is this not the right way to go?


Solution

  • Yes, you could achieve what you desire by calling JavaScript function using onclick attribute on each p:menuitem element and not on the p:tabMenu.

    For example, for the "Selected" p:menuitem you could have

    <p:menuitem value=Selected" onclick="criteria_showOnlySelected(); return false;"/>
    

    The return false; is to prevent default action submit behaviour. Similarly, for the other two p:menuitems you need to call the other specific JavaScript functions.

    [NOTE from the OP: This answer gives the crucial JavaScript call logic, but a little extra work was required to change the selected tab. See the edited question above for the full final solution.]