A <form> has different buttons. On the submit event I would like to know what button was clicked. I had the idea that the formaction attribute on the button could be used for this. On MDN it says that the formaction attribute:
Overrides the action attribute of the button's form owner.
But when getting the form action this value does not change according to the formaction. So how can I get the value of formaction or do you have any other suggestions for solving this?
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
console.log(e.target.action);
switch (e.target.action) {
case 'a':
// do "a" stuff
break;
case 'b':
// do "b" stuff
break;
}
});
<form name="form01" action="default">
<button formaction="a">A</button>
<button formaction="b">B</button>
</form>
Check out e.submitter. it'll give you the element that submitted the form
Add value to button and then use submitter as below.
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
console.log(e.submitter.value);
switch (e.submitter.value) {
case 'a':
// do "a" stuff
break;
case 'b':
// do "b" stuff
break;
}
});
<form name="form01" action="default">
<button value="a">A</button>
<button value="b">B</button>
</form>
If a formaction is attached to button to override submit event then you need to grab the element which have current focus after submit event is sent therefore to grab active element value use document.activeElement
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
let action = document.activeElement.getAttribute("formaction");
console.log(action);
switch (action) {
case 'a':
// do "a" stuff
break;
case 'b':
// do "b" stuff
break;
}
});
<form name="form01" action="default" method="get">
<button formaction="a">A</button>
<button formaction="b">B</button>
</form>