JSF - 如何为<h:commandButton>实现JavaScript的“确定要执行吗?”提示

16
在我的JSF 1.2 web应用程序中,我有一个页面,其中包含一个<h:commandButton>,该按钮调用后端bean上的动作方法。此操作将导致数据库中的数据被删除/替换,因此我希望避免用户意外单击该命令按钮。
我想使用JavaScript实现一个简单的“您确定吗?”提示,包括“Yes/No”或“OK/Cancel”选项。我不太擅长JavaScript,以前也从未将JavaScript与JSF混合使用过。是否有人可以提供一个代码片段来展示如何实现这个功能?
这里是我JSP页面中声明命令按钮的部分:
<h:commandButton 
    id="commandButtonAcceptDraft"
    title="#{bundle.tooltipAcceptDraft}" 
    action="#{controller.actionReplaceCurrentReportWithDraft}" 
    image="/images/checkmark.gif">
</h:commandButton>

解决方案:

BalusC提供的解决方案很有效。我想补充说明,使用资源包中的文本作为提示文本也很容易。在我的页面上,我使用如下元素加载资源包:

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

<f:loadBundle> 必须放在你的<f:view> 内部。然后我按照BalusC提供的代码将一个来自我的资源包的字符串替换为命令按钮元素中的“Are you sure?”文本,像这样:

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

我在英文资源文件中有一行内容(这个文件只是一个键值对的纯文本文件),看起来像这样:

# text displayed in user prompt when calling confirm()
confirmationTextAcceptDraft=This will overwrite the current report and cannot be undone. Are you sure?
4个回答

32

使用 JavaScript 的 confirm() 函数。它会返回一个 boolean 值。如果返回 false,则会阻止按钮的默认操作,否则会继续执行。

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

由于它已经返回了boolean,所以绝对没有必要像其他答案建议的那样将其包装在一个if中。


@CoolBeans的解决方案在我的情况下是正确的,因为否则该操作会重新加载页面。我正在使用MyFaces和BootsFaces。 - MitchBroadhead
@MitchBroadhead 然后,JSF实现或相关组件库以不正确的方式生成onclick属性。只需查看生成的HTML输出并向负责开发人员报告问题即可。 - BalusC
1
我在BootsFaces提交了一个错误报告,Stephan现在已经修复了这个问题。 - MitchBroadhead

3
您可以将JavaScript添加到按钮的onclick事件中。
<h:commandButton  
    id="commandButtonAcceptDraft" 
    title="#{bundle.tooltipAcceptDraft}"  
    action="#{controller.actionReplaceCurrentReportWithDraft}"  
    onclick="return confirm('Are you sure?')"
    image="/images/checkmark.gif"> 
</h:commandButton> 

在外部脚本中添加事件比内联方式有优势。内联方式可以实现,但如果您需要将其添加到大量项目中或在未来需要更改消息,则不易于编辑。 - zzzzBov

2
这应该可以工作。理想情况下,它应该在一个JavaScript文件中。
<h:commandButton 
    id="commandButtonAcceptDraft"
    title="#{bundle.tooltipAcceptDraft}" 
    action="#{controller.actionReplaceCurrentReportWithDraft}" 
    image="/images/checkmark.gif"
     onclick="if (!confirm('Are you sure?')) return false">
</h:commandButton>

1
这是我情况下的正确解决方案。@BalusC的解决方案会导致MyFaces和BootsFaces重新加载页面。不确定原因。 - MitchBroadhead

1

我不确定你需要监听哪个事件(我猜测是onclick),因为我从未使用过JSF。一般来说,这应该可以工作。

var element = document.getElementById('commandButtonAcceptDraft');

element.onclick = function(e){
  return confirm('Are you sure etc...');
};

1
如果你想使用 JavaScript 的 getElementById 方法,那么我相信你需要包含表单名称。在 JSF 中,元素的实际 ID 会像这样:'formName:commandButtonAcceptDraft'。 - bmeding

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接