JavaScript如何在JSP上使用带有两个提交按钮的Confirm对话框进行onSubmit操作

7

我的表单目前有两个提交按钮。一个用于搜索,另一个用于“标记完成”功能。我需要仅在单击“标记完成”按钮以提交经过验证的表单时显示确认对话框。是否可能识别这一点?我当前拥有以下confirmComplete函数:

function confirmComplete() {
alert("confirmComplete");
var answer=confirm("Are you sure you want to continue");
if (answer==true)
  {
    return true;
  }
else
  {
    return false;
  }
}

任何帮助都将不胜感激!


你只能使用JavaScript - 将提交按钮设置为普通按钮类型="button",将每个按钮的onclick设置为不同的函数,如果要提交表单,只需使用JavaScript:[form_element].submit(); - Adidi
由于已经实施了其他功能,我必须将它们保留为type="submit"。 - Richard
6个回答

27
将“标记为完成”按钮的onclick属性设置为:
 onclick="return confirm('Are you sure you want to continue')" 

并从表单中删除confirmComplete函数


3
你可以这样放置按钮。
<input type="submit" value="Search" />
<input type="submit" value="Mark Complete" onclick="{return confirmComplete();}" />

当点击标记为完成按钮时,将调用confirmComplete函数,当用户在确认对话框中点击确定时,才会提交表格。


1
你需要在按钮点击事件中执行操作,而不是表单提交。没有跨浏览器的方法可以知道是什么提交了表单。

1
所以这里提供一个绕过解决方案:
<form id="frm" action="page.php" method="post" onsubmit="return onSubmit();">
    <input />
    <input type="submit" value="sub1" onclick="sub1();" />
    <input type="submit" value="sub2" onclick="sub1();" />
</form>
 <script type="text/javascript">
<!--
var frm = document.getElementById('frm');
function onSubmit(){
    return false;
}

function sub1(){
    alert('s1');
    frm.submit();
}

function sub2(){
    alert('s2');

}
 //-->
 </script>

有趣的解决方案。下面展示的返回确认方法是最简单的方法。 - Richard

0
当您调用"confirm()" JavaScript 弹出函数时,比如 onclick="return confirm('确定要继续吗?')",确认框会弹出一个消息为"确定要继续吗?"的对话框,其中包含"确定"和"取消"两个选项。当您点击"确定"时,它返回 true,并继续执行网页;如果您点击"取消",它将返回 false,并停止网页的进一步执行。

0

我不知道对于输入标签,但是直接在按钮上使用点击事件对我没有起作用。在我的情况下,表单立即被提交了。

这里有一个可能的解决方案,适用于有多个按钮的表单(其中只有一个按钮必须显示确认消息)

在视图中:

<FORM name="F_DESTINATION_DB" id="F_DESTINATION_DB" method="POST" onsubmit="return popConfirmationBox('<?php echo LanguageControler::getGeneralTranslation("DELETE_CONFIRMATION_MESSAGE", "Deleting is an irreversible action. Are you sure that you want to proceed to the deleting?");?> ','DELETE_DB_BUTTON')">

Javascript(在外部文件中以便于代码复用):
/**
* Display a confirmation message box to validate if we must post the page or not.
*
* @param message String to display
* @param tagId String id of the tag that must display the message.
*
* @return Boolean (confirmation)
*/  
function popConfirmationBox(message, tagId){

    var confirmation = true;

    if (typeof tagId === 'string' && document.activeElement.id.toUpperCase() === tagId.toUpperCase()) {

        if (typeof message === 'string' && message.length > 0) {

            confirmation = window.confirm(message);
        }
    }

    return confirmation;
}

我花了很多时间进行研究和测试才实现这个(需要很多研究和测试),但最终的代码非常简单。

默认情况下,我假设确认是肯定的(如果点击的按钮不是用于显示消息的按钮或用户没有提供有效的消息字符串)。

附加说明:当然,如果用户浏览器阻止客户端代码,则此代码将无法完成任务。

我希望它能帮助某些人,

来自蒙特利尔的Jonathan Parent-Lévesque


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