skip to Main Content

Let’s say you create a wizard in an HTML form. One button goes back, and one goes forward. Since the back button appears first in the markup when you press Enter, it will use that button to submit the form.

Example:

<form>
  <!-- Put your cursor in this field and press Enter -->
  <input type="text" name="field1" />

  <!-- This is the button that will submit -->
  <input type="submit" name="prev" value="Previous Page" />

  <!-- But this is the button that I WANT to submit -->
  <input type="submit" name="next" value="Next Page" />
</form>

I would like to get to decide which button is used to submit the form when a user presses Enter. That way, when you press Enter the wizard will move to the next page, not the previous. Do you have to use tabindex to do this?

2

Answers


  1. You can achieve it with JS, add this to your page.

    <script>
          const form = document.getElementById("wizard-form");
          const nextButton = form.querySelector('input[name="next"]');
        
          form.addEventListener("keydown", (event) => {
            if (event.key === "Enter") {
              event.preventDefault();
              nextButton.click();
            }
          });
    
    </script>
    
    Login or Signup to reply.
  2. use this code 13 for press Enter button

    <script>
      function checkEnter(event) {
        if (event.keyCode === 13) {
          event.preventDefault();
          document.getElementById('nextButton').click();
        }
      }
    </script>
    
    <form>
      <input type="text" name="field1" id="field1" onkeydown="checkEnter(event)" />
      <input type="submit" name="prev" value="Previous Page" />
      <input type="submit" name="next" value="Next Page" id="nextButton" />
    </form>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search