我可以确定在 javascript 中使用了哪个提交按钮吗?

新手上路,请多包涵

我有一个非常简单的表单,其中包含一个名称字段和两个提交按钮:“更改”和“删除”。提交表单时,我需要在 javascript 中进行一些表单验证,因此我需要知道单击了哪个按钮。如果用户按下回车键,“更改”值就是发送到服务器的那个值。所以真的,我只需要知道是否点击了“删除”按钮。

我可以确定单击了哪个按钮吗?或者我是否需要将“删除”按钮从提交更改为常规按钮并捕获其 onclick 事件以提交表单?

表格如下所示:

  <form action="update.php" method="post" onsubmit="return checkForm(this);">
    <input type="text" name="tagName" size="30" value="name goes here" />
    <input type="hidden" name="tagID" value="1" />
    <input type="submit" name="submit" value="Change" />
    <input type="submit" name="submit" value="Delete" />
 </form>

checkForm() 函数中, form["submit"] 是一个节点列表,不是我可以获取值的单个元素。

原文由 Scott Saunders 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 218
2 个回答

您还可以通过多种不同的方式使用 onclick 事件来解决该问题。

例如:

 <input type="submit" name="submit" value="Delete"
       onclick="return TryingToDelete();" />

在JavaScript中的 TryingToDelete() 函数中,做你想做的,然后 return false 如果不想继续删除。

原文由 Glen Little 发布,翻译遵循 CC BY-SA 2.5 许可协议

这是使用 jQuery 的一种 不显眼的方法……

 $(function ()
{
    // for each form on the page...
    $("form").each(function ()
    {
        var that = $(this); // define context and reference

        /* for each of the submit-inputs - in each of the forms on
           the page - assign click and keypress event */
        $("input:submit", that).bind("click keypress", function ()
        {
            // store the id of the submit-input on it's enclosing form
            that.data("callerid", this.id);
        });
    });

    // assign submit-event to all forms on the page
    $("form").submit(function ()
    {
        /* retrieve the id of the input that was clicked, stored on
           it's enclosing form */
        var callerId = $(this).data("callerid");

        // determine appropriate action(s)
        if (callerId == "delete") // do stuff...

        if (callerId == "change") // do stuff...

        /* note: you can return false to prevent the default behavior
           of the form--that is; stop the page from submitting */
    });
});

注意: 此代码使用 id 属性来引用元素,因此您必须更新标记。如果您希望我更新答案中的代码以使用名称属性来确定适当的操作,请告诉我。

原文由 cllpse 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题