2

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?

Neo
  • 1,337
  • 4
  • 21
  • 50
  • Did you try if it is added and removed? Checked with a browser developer tool? Checked the network traffic (the button does update with ajax) – Kukeltje Nov 24 '15 at 10:39
  • 1
    Possible duplicate of [How to update the style of a JSF component at runtime](http://stackoverflow.com/questions/7663296/how-to-update-the-style-of-a-jsf-component-at-runtime) – Kukeltje Nov 24 '15 at 11:03
  • And if you don't want to call any server-side method, add `type="button"` to the commandButton. That prevents a server call. See the PrimeFaces documentation – Kukeltje Nov 24 '15 at 11:12

2 Answers2

3

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.

esel
  • 901
  • 9
  • 20
0

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

LarsBr
  • 1
  • 1
  • _"So it is impossible to change a style class. But not in combination with a commandButton"_ hmmm... kind of contradictory ;-) At least this suggests it should work with a commandButton. The reasoning is not fully right though. What the OP suspects is that all that happens is updating a button client-side. But OP does not take the ajax call and update into account. That update removes the class again. – Kukeltje Nov 24 '15 at 10:40
  • The more i think about the more it is clear for me. I think its normal that an update removes the style classes. It is possible to set the style classes as property to a bean and get it via EL? – LarsBr Nov 24 '15 at 11:00
  • Yes, see the other answer, but all these kind of 'basic' question very, very often already have a Q/A in Stackoverflow. – Kukeltje Nov 24 '15 at 11:01