简体   繁体   中英

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?

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, eg

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

And in the action you can then toggle the variable.

Have you tried just to update the commandButton instead the whole form?

<p:commandButton id="my button" update="@this" onclick="toggleButton();"/>

But for other reasons... i just noticed that primefaces sometimes removes all css classes from a component in a very last step just to put their own classes again. So it is impossible to change a style class. But not in combination with a commandButton

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM