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.
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.
- 1 Your code works fine for me: jsfiddle/a80wnex6 – Unmitigated Commented Aug 23, 2018 at 15:12
-
Code is working fine (thx for example code), but my problem is how to get the new action set by
formaction
inside asubmit
event. – Jastrzebowski Commented Aug 23, 2018 at 15:34
2 Answers
Reset to default 4You 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>
You can use submitter
property of SubmitEvent
and check that formaction
attribut is filled
https://developer.mozilla/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 {
...
}