9

I have a <h:commandButton> in my XHTML page. I want the button to be disabled as soon as I click the button. Then the button should call the action. My button gets disabled as I expect but the problem is that the action is not fired.
<h:commandButton value="Go" onclick="this.disabled=true" action="#{bean.go()}"/>

But if I remove the onclick attribute the action is fired.

Or if I used an <a4j:commandButton> it works.
Following a4j button works.
<a4j:commandButton value="Go" onclick="this.disabled=true" action="#{bean.go()}"/>

How can I disable a <h:commandButton> after being clicked, so that the action still fires?

phant0m
  • 16,595
  • 5
  • 50
  • 82
prageeth
  • 7,159
  • 7
  • 44
  • 72
  • 1
    check this stack answer http://stackoverflow.com/a/2594864/1358004 – Viral Shah Oct 29 '12 at 06:35
  • @ViralShah : I want the button to be disabled after clicked once on it. Is your solution still applicable? You meant `onclick="this.disabled = 'disable'"`? It also doesn't work. :( – prageeth Oct 29 '12 at 06:40
  • Why don't you set some arbitrary value as `false` when the button is clicked? But before just setting the value, you should first check for this value being `true` before proceeding. That way, it may not look disabled, but will technically be disabled. – Ian Oct 29 '12 at 06:43
  • @ianpgall : Good idea. The problem is the button still looks enabled. – prageeth Oct 29 '12 at 07:45
  • If you use the ``, you can use the `oncomplete` javascript method that executes after the action is performed: `` – Luiggi Mendoza Oct 29 '12 at 14:04
  • @LuiggiMendoza The `oncomplete` feature has nothing to do with this - the problem is before the AJAX event even gets fired, and is prevented because the button is disabled because of the `onclick` code – Ian Oct 29 '12 at 19:02

1 Answers1

7

Use setTimeout , that way the action will be fired and the button will be disabled...

<h:commandButton value="Go"
   onclick="setTimeout('this.disabled = true;', 50);" 
   action="#{bean.go()}"/>

You can also take a look at the following question too :How can I disable an h:commandButton without preventing the action and actionListener from being called?

Community
  • 1
  • 1
Daniel
  • 36,833
  • 10
  • 119
  • 200
  • Nice idea. Can it be called as a 'hack'? It worked well.I used it as `setTimeout('this.disabled = true', 50);`. Thanks. – prageeth Oct 29 '12 at 07:41
  • You are welcome , I guess that yes... Looks like a *hack/workaround* to me too... – Daniel Oct 29 '12 at 07:51