Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  151] [ 4]  / answers: 1 / hits: 18129  / 14 Years ago, wed, november 10, 2010, 12:00:00

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?

More From » java

 Answers
10

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.


[#95015] Monday, November 8, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
bryantc questions
Fri, Aug 13, 21, 00:00, 3 Years ago
Tue, Mar 30, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;