Disable commandButton in JSF

Jamie McIlroy picture Jamie McIlroy · Aug 6, 2009 · Viewed 13.9k times · Source

This seems like it should be pretty straightforward but I'm not feeling it.

I have a JSF CommandButton that executes a long running serverside task (10-15 seconds). I've seen forms where the button context changes after it's been clicked (The label on the button changes and the button becomes disabled until the processing is complete).

I'm using ICEFaces and have the disabled property set to a boolean on the underlying page code.

The action listener bound to the button changes that boolean to disable it but alas, no changes on the JSP.

Anyone?

Answer

Romain Linsolas picture Romain Linsolas · Aug 7, 2009

What you can do is to change the status of the button using Javascript:

<h:commandButton ... onclick="this.disabled=true"/>



Edit regarding the comment:

If the previous code does not submit the form, then you have to disable the button a little time after the click, not "during" the click itself. You can do that using the following code:

<h:commandButton ... onclick="setTimeout('this.disabled=true', 100);"/>

I'm not sure if the fact to use the this keyword directly in the setTimeout method will work correctly. If not, you can use another way to do that:

<h:commandButton ... onclick="disableButton(this.id);"/>

with the following Javascript function:

function disableButton(buttonId) {
    setTimeout("subDisableButton(" + buttonId + ")", 100);
}

function subDisableButton(buttonId) {
    var obj = document.getElementById(buttonId);
    if (obj) {
        obj.disabled = true;
    }
}

(I'm sure this code can be enhanced, thus)