Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF - How do I implement a JavaScript "Are you sure?" prompt for a <h:commandButton>

In my JSF 1.2 webapp I have a page with a <h:commandButton> that invokes an action method on a backing bean. This action will cause data to be removed/replaced in the database, so I want to avoid any situations where the user accidentally clicks on the command button.

I would like to implement a simple "Are you sure?" prompt with "Yes/No" or "OK/Cancel" options using JavaScript. I'm not great with JavaScript and I have never mixed JavaScript with JSF before. Can anyone provide a code snippet to show me how to implement this?

Here is the piece of my JSP page where I declare the command button:

<h:commandButton 
    id="commandButtonAcceptDraft"
    title="#{bundle.tooltipAcceptDraft}" 
    action="#{controller.actionReplaceCurrentReportWithDraft}" 
    image="/images/checkmark.gif">
</h:commandButton>

SOLUTION:

The solution provided by BalusC worked just fine. I wanted to also mention that it is easy to use text from a resource bundle as the prompt text. On my page, I load the resource bundle with an element like this:

<f:loadBundle basename="com.jimtough.resource.LocalizationResources" var="bundle" />

The <f:loadBundle> must be inside your <f:view>. Then I add the code provided by BalusC to my command button element but substitute a string from my resource bundle for the 'Are you sure?' text, like this:

<h:commandButton 
    id="commandButtonAcceptDraft"
    title="#{bundle.tooltipAcceptDraft}" 
    action="#{controller.actionReplaceCurrentReportWithDraft}" 
    image="/images/checkmark.gif"
    onclick="return confirm('#{bundle.confirmationTextAcceptDraft}')">
</h:commandButton>

The line in my English resource file (just a plain text file with key/value pairs) looks like this:

# text displayed in user prompt when calling confirm()
confirmationTextAcceptDraft=This will overwrite the current report and cannot be undone. Are you sure?
like image 573
Jim Tough Avatar asked Nov 10 '10 20:11

Jim Tough


1 Answers

Use the JavaScript confirm() function. It returns a boolean value. If it returns false, then the button's default action will be blocked, else it will be continued.

<h:commandButton onclick="return confirm('Are you sure?')" />

Since it already returns boolean, there's absolutely no need to wrap it around in an if a suggested by other answers.

like image 176
BalusC Avatar answered Sep 28 '22 12:09

BalusC