【问题标题】:HTML Form and Javascript ConfirmationHTML 表单和 Javascript 确认
【发布时间】:2023-03-26 08:24:01
【问题描述】:

我在提交表单和 Javascript 确认时遇到问题。基本上,按下“提交”按钮时会调用以下 Javascript。

function confirmation() {
    var answer = confirm("Are you sure you wish to edit?")
    if (answer)
    {
        window.location = "#editform2";
    }
}

但是,当我点击取消而不是确定时,Javascript 正确执行,因为我查看了地址栏并且它没有更新到#editform2。但是,表单仍然提交。似乎刷新了页面。以下是表格中的相关部分:

//Form is encoded in PHP
<form method=\"post\">
//Form is in here
<input type=\"submit\" value=\"Edit\" onclick=\"confirmation()\">

所以表单不知道它要去哪里,它只是刷新页面,而页面恰好也是处理器。因此,即使我单击了取消,它仍在处理中,并且 Javascript 应该将它保持在同一页面上。除了将处理移动到不同的页面,我的解决方案是什么?

【问题讨论】:

    标签: javascript webforms forms confirm


    【解决方案1】:

    它的工作原理是这样的,因为它是一个 sumbit 按钮,并且在每种情况下都会提交表单。为表单分配一个 id 并更改输入类型:

    <form method="post" id="formid">
    <input type="button" value="Edit" onclick="confirmation()">
    

    并在点击时调用此函数:

    function confirmation() {
        var answer = confirm("Are you sure you wish to edit?")
        if (answer)
        {
            document.getElementById("formid").submit();
        }
    }
    

    【讨论】:

    • 不是每次都提交表单,如果方法返回false则不会提交表单...
    【解决方案2】:

    不要使用提交按钮的onclick事件,使用表单的onsubmit事件:

    document.forms[0].onsubmit = function () {
        return confirm("Are you sure you wish to edit?");
    }
    

    您可能想在表单中添加一个 id 属性来识别它。

    在 JavaScript 代码上保持事件绑定;不在 HTML 的内联属性上,使您的代码更易于维护和调试。

    【讨论】:

    • +1,但document.forms[0] 不是一个很好的可维护性解决方案。给表单一个名称或 ID 会更好。
    • 同意,谢谢,仅供参考,这就是为什么我建议添加一个 id...
    【解决方案3】:

    尝试:

    return answer;
    

    在函数的末尾并确保 onclick 方法返回 this。像这样:

    <input type="submit" value="Edit" onclick="return confirmation()">
    

    这会使函数返回 false 并且不会发布表单。

    【讨论】:

      猜你喜欢
      • 2014-10-01
      • 1970-01-01
      • 2012-07-23
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 2013-06-03
      • 2011-11-25
      相关资源
      最近更新 更多