Search code examples
cssjsfprimefacestoggleclass

primefaces toggle (command)button


I'm trying to use a primefaces commandbutton as toggle button. My idea was to add a css class with the desired style, in this way:

<p:commandButton id="mybutton" onclick="toggleButton();"/>

javascript:

function toggleButton() {
        $(this).toggleClass("myCustomClass");
    return true;
}

css:

.myCustomClass{
 background-color: red;
}

For some reasons, this doesn't work. My supposition is that PF does some magic with button's style, and my class is added and right away removed. Some hint?


Solution

  • The reason why your style is not changed, may be that the <p:commandButton> makes an ajax request and updates parts of the view. (See Attribute update of the button.) Then the changes made by JavaScript are gone. If you need to make an ajax request on click of the button, it may be best to bind the styleClass value to an attribute on a server side bean, e.g.

    <p:commandButton styleClass="#{myBean.buttonEnabled ? '' : 'myCustomClass'}" 
                     action="myBean.someAction()"... 
                     update="@this" />
    

    And in the action you can then toggle the variable.