为一个表单调试两个按钮

Debugging two buttons for one form

我看过 this question and this question as well,但使用 <button> 标签的解决方案对我不起作用。

我认为这是因为我正在使用 FormData,但我认为 FormData 会获取所有提交的键和值。

这是一个简单的 JSFiddle 我正在尝试做的事情,但它不起作用。我希望看到 firstsecond 值出现在 FormData 对象中,但只有 input-data 出现。

我需要能够确定提交表单时按下了哪个按钮。

function handleSubmit(event) {
    event.preventDefault(); // don't have the browser refresh on submit
    const formData = new FormData(event.target);
    for (var pair of formData.entries()) {
        console.log(pair[0]+ ' ==> ' + pair[1]);
    }
}

const form = document.getElementById('form');

form.addEventListener('submit', handleSubmit);
  <form id="form">
    <input name="input-data"/>
    <button type="submit" name="action" value="first">Submit</button>
    <button type="submit" name="action" value="second">Another Submit</button>
  </form>

我认为使用 FormData 无法完成,

你必须自己编写代码,像这样:

const MyForm = document.getElementById('my-form')

var lastClick = null

MyForm.onclick=evt=>
  {
  lastClick = evt.target.matches('button[type=submit]') 
               ? evt.target.name 
               : null
  }

MyForm.onsubmit=evt=>
  {
  evt.preventDefault()
  console.clear()
  console.log ( 'submit by', lastClick) 
  let formData = new FormData(MyForm);
  for (let pair of formData.entries())
    {
    console.log(pair[0],' ==> ',pair[1])
    }
}
<form id="my-form">
    <input name="input-data"/>
    <button type="submit" name="first">Submit</button>
    <button type="submit" name="second">Another Submit</button>
  </form>

FormData not collect value of buttons. You can set value for a hidden input like this:

function handleSubmit(event) {
    event.preventDefault(); // don't have the browser refresh on submit

    document.getElementById('action').value = event.submitter.value;

    const formData = new FormData(event.target);
    for (var pair of formData.entries()) {
        console.log(pair[0]+ ' ==> ' + pair[1]);
    }
}

const form = document.getElementById('form');

form.addEventListener('submit', handleSubmit);
<form id="form">
  <input name="input-data"/>
  <input type="hidden" name="action" id="action" value=""/>
  <button type="submit" name="action" value="first">Submit</button>
  <button type="submit" name="action" value="second">Another Submit</button>
</form>

Cross Browser Solution

function handleSubmit(event) {
  const formData = new FormData();
  formData.append("input-data", document.getElementById("input-data").value)
  formData.append(event.name, event.value);

  for (var entry of formData) {
      console.log(entry[0] + ' => ' + entry[1]);
  }
}
<form id="form">
  <input id="input-data"/>
  <button type="button" name="action" value="first" onclick="handleSubmit(this)">Submit</button>
  <button type="button" name="action2" value="second" onclick="handleSubmit(this)">Another Submit</button>
</form>