'How to get formaction in submit event?

Having a simple form with two submit buttons, how can I get the formaction attribute in a submit event?

HTML code:

<form id="FORM" action="/original">
  <input type="text">
</form>

<button form="FORM">original</button>
<button form="FORM" formaction="/formaction">formaction</button>

When submitting using formaction button action of the form is still original in the event.



Solution 1:[1]

You can get the overridden form action by grabbing the element which currently has focus (after the submit event was sent) using document.activeElement

You can see if a formaction override is attached to the button that sent the submit event, otherwise if there is none, then use the original action

document.getElementById("FORM").addEventListener("submit", handleForm);

function handleForm(e) {
  e.preventDefault(); // for this example only

  let formAction = e.target.getAttribute("action");
  let activeElementAction = document.activeElement.getAttribute("formaction");
  let action = activeElementAction || formAction;
  console.log(action);
}
<form id="FORM" action="/original">
  <input type="text">
</form>

<button form="FORM">original</button>
<button form="FORM" formaction="/formaction">formaction</button>

Solution 2:[2]

You can use submitter property of SubmitEvent and check that formaction attribut is filled https://developer.mozilla.org/en-US/docs/Web/API/SubmitEvent

This property is referenced in originalEvent property of JQuery submit event

var submitter = $(event.originalEvent.submitter)

if (submitter.attr('formaction')) {
    ...     
} else {
    ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew Lohr
Solution 2 Gregory Elleouet