How to add a confirm dialog to a command button?

I’d think this would work just fine, but it seems to prevent the action function from firing regardless of the confirm response

<apex:commandButton value="Remove All" action="{!removeAll}" rerender="form"
     status="LoadingStatus" onclick="return confirm('Are you sure?');"/>

Answer

I know this has been answered but I thought I would toss my hat into the ring. Taking a look at the code generated by the commandButton tag, the onclick code goes before salesforce’s own code to call the controller method. What this means is

onclick="return confirm('Are you sure?');"

is always returning before calling the code to the controller method. What I have done is to wrap the return in an if statement and call it only if the condition is correct. The code below will call return if the confirmation is false.

onclick="if(!confirm('Are you sure?')){return false};"

Attribution
Source : Link , Question Author : Ralph Callaway , Answer Author : josy

Leave a Comment