简体   繁体   English

同一个表单的两个提交按钮(具有不同的操作)

[英]Two submit buttons (with different action) for the same form

I have a html form which requires two submit buttons.我有一个需要两个提交按钮的 html 表单。 Each button when clicked needs to catch the event (form submission) then process form data and move forward or backward in GUI depending in which one of the two buttons was pressed.单击时,每个按钮都需要捕获事件(表单提交),然后处理表单数据并在 GUI 中向前或向后移动,具体取决于按下了两个按钮之一。

I haven't found a way to catch in Javascript which button was pressed in submit event handler.我还没有找到一种方法来在 Javascript 中捕获在提交事件处理程序中按下了哪个按钮。 When using click event handler no form is attached to this action.使用 click 事件处理程序时,此操作不会附加任何表单。 Any advice?有什么建议吗?

Instead of click event, I prefer using submit event of forms, which includes a submitter property indicating which button was clicked.而不是click事件,我更喜欢使用表单的submit事件,它包括一个submitter属性,指示点击了哪个按钮。 (Bonus: form get validated before submit fired). (奖励:表单在submit之前得到验证)。

The event object has a property on it called target which is a reference to the DOM node that triggered the event. 事件对象具有一个称为target的属性,该属性是对触发事件的DOM节点的引用。 It should contain the button that was clicked. 它应该包含被单击的按钮。

Use 2 different names for the 2 buttons and capture the click event. 为2个按钮使用2个不同的名称,并捕获click事件。 The name would let you identify and work upon the specified button pressed. 该名称可让您识别并按指定的按钮进行操作。

As shown in https://jsfiddle.net/0fuq5dhf/1/ : https://jsfiddle.net/0fuq5dhf/1/所示:

var form = document.getElementById("frmData");
form.addEventListener("click", function(event) {
    var formData = $( '#' + event.currentTarget.id ).serialize();
  if(event.target.id == "submit1") {
    //Process for first submit button
    console.log(formData);
  } else {
    //process for the 2nd submit button
    console.log(formData);
  }

});

you can get the target to determine which button is clicked and serialize the form data to process based on button clicked. 您可以获取目标以确定单击哪个按钮,并根据单击的按钮序列化要处理的表单数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM