Get form action and method from form submit event

Viewed 130

I have the below code which intercepts the submit event from a form. How can I get the path and method from the event (i.e. the action and method attributes from the form)? I've tried logging out the event and looking through it's properties but it is massive and I couldn't find them, and the Mozilla docs here just lists one property and says the rest inherits from Event. If is not possible I assume I can just get the values directly from the form element, but I would prefer to get them from the event because I assume it does extra things like expands a relative URL in the action attribute.

const form = document.querySelector("form");
form.addEventListener("submit", e => {
  e.preventDefault();
  console.log(e);
});
1 Answers

You can either access it from the form variable you created, or you can access the event's "base" target, i.e. the element the listener was attached to, using event.currentTarget.

Here is an example:

const form = document.querySelector("form");
form.addEventListener("submit", event => {
  event.preventDefault();
  
  const target = event.currentTarget;
  
  console.log(target.method, target.action);
  console.log(form.method, form.action);
  console.log(form === target)
});
<form action="#/action-reaction" method="post">
<button type="submit">Submit</button>
</form>

Related