最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get formaction in submit event? - Stack Overflow

programmeradmin1浏览0评论

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.

Share Improve this question edited Aug 23, 2018 at 19:02 Unmitigated 89.9k12 gold badges99 silver badges104 bronze badges asked Aug 23, 2018 at 15:02 JastrzebowskiJastrzebowski 1942 silver badges7 bronze badges 2
  • 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 a submit event. – Jastrzebowski Commented Aug 23, 2018 at 15:34
Add a ment  | 

2 Answers 2

Reset to default 4

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>

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 {
    ...
}
发布评论

评论列表(0)

  1. 暂无评论