JSFiddle - React, Tailwind, and code Playground

by Carson Evans

HTML

<form id="myForm" action="/path/to/endpoint" method="POST">
   <input type="text" name="foo" value="foo">
   <input type="text" name="bar" value="bar">
   
   <input type="submit" name="submit" value="Submit1">
   <input type="submit" name="submit" value="Submit2">
</form>

JavaScript

const myForm = document.querySelector("#myForm");

myForm.addEventListener("submit", async (event) => {
	event.preventDefault();
	const formData = new FormData(event.target);
  console.log(formData.get("submit")) // Darn this didnt work as expected
  
  const buttonClicked = document.activeElement; // This works to get whatever button was cicked
  
  console.log(buttonClicked.value);
  
  const response = await fetch(event.target.action, {
  	method: event.target.method,
    body: formData
  });
  
  if (response.ok) {
  	// do something
  } else {
  	// handle error
  }
});