Home > Back-end >  How to get the form action on submit when using the formaction attribute on a button
How to get the form action on submit when using the formaction attribute on a button

Time:03-02

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>

CodePudding user response:

Check out e.submitter. it'll give you the element that submitted the form

CodePudding user response:

There is little trick on this, here if a formaction is attached to button to override submit event. You need to grab the element which currently have focus after submit event is sent therefore for you need to use document.activeElement to grab active element value.

document.forms.form01.addEventListener('submit', e => {
  e.preventDefault();
  
  let formAction = e.target.getAttribute("action");
  let activeElementAction = document.activeElement.getAttribute("formaction");
  let action = activeElementAction || 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 type='submit' formaction="a">A</button>
  <button type='submit' formaction="b">B</button>
</form>

CodePudding user response:

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>

  • Related