How to add a confirm dialog to a command button?

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};"

In my case, it was returning to controller method for both options( true or false) so then i changed it to the code below and it started to work.

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

Was able to get this to work with an action function, but hopefully someone in the community might have cleaner way to handle this.

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

Tags:

Visualforce