如何知道哪个提交按钮触发了 onsubmit 事件

发布于 2024-09-15 05:46:12 字数 139 浏览 6 评论 0原文

当表单中有多个提交按钮时,是否有一种方法可以知道哪一个触发了 onsubmit 事件,而无需向按钮本身添加代码?


编辑:我需要在客户端进行检查,即使用 JavaScript。

When you have more than one submit button in a form, is there a way to know which one fired the onsubmit event without adding code to the buttons themselves?


Edit: I need to do the check on the client-side, i.e. with JavaScript.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

左岸枫 2024-09-22 05:46:12

“提交”事件不是由按钮触发的,而是由“表单”触发的。快速测试证明了这一点:

  <form id="myform">
     <input id="email" type="text" value="1st Email" />
     <input id="action1" type="submit" value="Action 1" />
     <input id="action2" type="submit" value="Action 2" />
  </form>

  <script type="text/javascript">

     document.getElementById("myform").onsubmit = function(evt)  {
        var event = evt || window.event;
        alert(event.target.id); // myform
        alert(event.explicitOriginalTarget.id); // action2 (if action2 was clicked)
                                                // but only works in firefox!
     }

  </script>

尽管在 Firefox 中,您可以使用事件的 event.explicitOriginalTarget 属性来获取单击的输入(提交),从而触发提交事件。 (如果你想知道)

所以对你来说最好的选择是:

  • 为你的提交按钮设置不同的值,或者
  • 将它们作为普通按钮并通过 javascript 单击处理程序。

The "submit" event is not fired by the button, but its fired by the "form". A quick test proves this:

  <form id="myform">
     <input id="email" type="text" value="1st Email" />
     <input id="action1" type="submit" value="Action 1" />
     <input id="action2" type="submit" value="Action 2" />
  </form>

  <script type="text/javascript">

     document.getElementById("myform").onsubmit = function(evt)  {
        var event = evt || window.event;
        alert(event.target.id); // myform
        alert(event.explicitOriginalTarget.id); // action2 (if action2 was clicked)
                                                // but only works in firefox!
     }

  </script>

Although in firefox, you can use event.explicitOriginalTarget property on event to get the input (submit) that was clicked causing the submit event to be fired. (if you want to know)

So best options for you are:

  • Have a different value to your submit buttons OR
  • Have those as normal buttons and click handlers to them via javascript.
初与友歌 2024-09-22 05:46:12

SubmitEvent 对象上有一个 submitter 属性。

请参阅示例:

<!DOCTYPE html>
<html>
<body>
<form action="./test.html" onsubmit="myFunction(event)">
  Enter name: <input type="text" name="fname">
  <button id="firstButton" type="submit">Button 1</button>
  <button id="secondButton" type="submit">Button 2</button>
</form>

<script>
function myFunction(event) {
  // This should log id of the button that was used for submition
  console.log(event.submitter.id); 

  // Prevent sending the form (just for testing)
  event.preventDefault();
}
</script>

</body>
</html>

请参阅 https://developer.mozilla.org/ en-US/docs/Web/API/SubmitEvent/submitter

There is a submitter attribute on SubmitEvent object.

See example:

<!DOCTYPE html>
<html>
<body>
<form action="./test.html" onsubmit="myFunction(event)">
  Enter name: <input type="text" name="fname">
  <button id="firstButton" type="submit">Button 1</button>
  <button id="secondButton" type="submit">Button 2</button>
</form>

<script>
function myFunction(event) {
  // This should log id of the button that was used for submition
  console.log(event.submitter.id); 

  // Prevent sending the form (just for testing)
  event.preventDefault();
}
</script>

</body>
</html>

See https://developer.mozilla.org/en-US/docs/Web/API/SubmitEvent/submitter

倾听心声的旋律 2024-09-22 05:46:12

每个按钮上都有一个事件侦听器是否算作添加代码?否则,无法查看哪个按钮触发了提交事件,除非您想认真计算事件期间的鼠标位置并将其与按钮位置进行比较。

否则,下一个最好的办法是为按钮的单击事件分配一个事件处理程序,并将该按钮的名称分配给一个可以在表单的提交事件中检查的变量。

Does having an event listener on each button count as adding code? Otherwise, there's no way to see what button triggered the submit event, unless you want to get down and dirty and calculate the mouse position during the event and compare it to button positions.

Otherwise, the next best thing would be to assign an event handler for the click event of button and assign the name of that button to a variable you can check in the form's submit event.

红焚 2024-09-22 05:46:12

我能想到的有几种方法。

您可以使用不同的值,并且您不显眼的 javascript 可以提供帮助。

关于此方法的一次讨论(为每个按钮使用不同的值)如下:

http:// www.chami.com/tips/internet/042599I.html

我倾向于为每个按钮使用不同的 name 属性。

关于此的博客在这里: http://www.codetoad.com/javascript/multiple.asp

我不遵循其中任何一个,哪种方法最有效取决于不同的因素,例如,您是否在 javascript 中处理提交按钮,或者服务器是否会获取表单,然后必须弄清楚找出用户想要什么。

就个人而言,我更喜欢使用 ajax 方法,现在,我只是在页面加载后使用不显眼的 javascript 将事件附加到按钮,然后根据用户选择调用正确的函数,但这取决于您是否可以添加一个脚本链接到html页面。

更新:

为了用javascript做到这一点,最简单的方法是在单击按钮时附加一个事件,然后查看名称来决定如何处理它。

实际上,表单从来不需要真正提交到服务器,但是您可以通过包装参数(选项)并将它们发送到服务器来在后台处理所有事情,并让用户知道结果。

There are a couple of ways that I can think of.

You can use different values, and your unobtrusive javascript can help with it.

One discussion on this approach (using different values for each button) is here:

http://www.chami.com/tips/internet/042599I.html

I tend to go with using different name attributes for each button.

A blog on that is here: http://www.codetoad.com/javascript/multiple.asp

I don't follow either of these, which approach will work best is going to depend on different factors, such as, are you handling the submit buttons in javascript, or will the server get the form, then have to figure out what the user wanted.

Personally, I prefer to use the ajax approach, now, where I just attach events to the buttons after the page is loaded, using unobtrusive javascript, and then based on the user choice call out to the correct function, but that depends on whether you can add a script link to the html page.

UPDATE:

In order to do this with javascript, the simplest way is to attach an event on the click of the button, and then look at the name to decide how to handle it.

In actuality, the form never truly has to be submitted to the server, but you can handle everything in the background by wrapping up the parameters (options) and sending them to the server, and let the user know the results.

轻拂→两袖风尘 2024-09-22 05:46:12

抱歉要预热这个非常旧的线程。该问题尚未在此得到解答,但之前仅给出了实际解决方法的方法。

但事件对象确实携带有关哪个对象发起它的信息。在处理程序 b4submit(e) 中,您可以像这样获取提交按钮:

function b4submit(e) {
    var but = e.originalEvent.explicitOriginalTarget;
    ...
}

And but 是一个 HTML 对象,具有您为其分配的所有属性,例如名称、ID、值等

。经过一些调试后遇到了这个问题,我认为作为这个问题的干净解决方案可能会引起更广泛的兴趣。

Sorry to warm up this very old thread. The question hadn't been answered here but only approaches for practical workarounds have been given here before.

But the event-object does carry information about which object has initiated it. In a handler b4submit(e) you can get the submit-button like this:

function b4submit(e) {
    var but = e.originalEvent.explicitOriginalTarget;
    ...
}

And but is an HTML Object with all the attributes you've assigned it with, like name, id, value etc.

I came across this after some debugging, and I thought it might be of a wider interest as a clean solution for this issue.

堇年纸鸢 2024-09-22 05:46:12

对我来说,最简单的选择是使用 document.activeElement 如果你想获取 id 使用 document.activeElement.id 如果你想获取文本内容您可以简单地输入 document.activeElement.textContent

  const onSubmit = () => {
    console.log('document.activeElement', document.activeElement.id)
    if (document.activeElement.textContent === 'Suivant') {
      handleNext()
      return
    }
    if (document.activeElement.textContent === 'Confirmer') {
      console.log('Payer')
      return
    }
  }

For me the simplest option that worked for me is to use document.activeElement if you want to get the id use document.activeElement.id if you want to get the text content you can simply put document.activeElement.textContent

  const onSubmit = () => {
    console.log('document.activeElement', document.activeElement.id)
    if (document.activeElement.textContent === 'Suivant') {
      handleNext()
      return
    }
    if (document.activeElement.textContent === 'Confirmer') {
      console.log('Payer')
      return
    }
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文