Skip to content
PHP Logo

How can you specify which submit button is triggered when pressing ENTER in a form with multiple submits?

When pressing ENTER in a form with multiple submit buttons, the default behavior is to trigger the first submit button in the form. To specify which submit button should be triggered, you can use JavaScript to capture the ENTER key press event and programmatically click the desired submit button based on its unique identifier.

php
<form id="myForm" method="post">
  <input type="text" name="input_field">
  <button type="submit" name="submit_button1" id="submit_button1">Submit 1</button>
  <button type="submit" name="submit_button2" id="submit_button2">Submit 2</button>
</form>

<script>
document.getElementById("myForm").addEventListener("keypress", function(e) {
  if (e.key === "Enter") {
    e.preventDefault();
    if (document.activeElement.id === "input_field") {
      document.getElementById("submit_button1").click();
    } else {
      document.getElementById("submit_button2").click();
    }
  }
});
</script>