0

If we have a form which we can submit it by pressing Enter key on the keyboard, so when we are on the form and then press Enter, what event first triggered, form submit event or keyboard (either of keydown, key press or keyup) event?!

Edition

Here is my test code for the above problem: https://codepen.io/ultimateblue-the-selector/pen/gOxrapj?editors=1111

html part:

<body>
    <div class="input__div">
        <form class="input__form" action="" method="post">
            <label for="type">Type</label>
            <select name="workout__type" id="type">
                <option selected value="Running">Running</option>
                <option value="Cycling">Cycling</option>
            </select>
            <label for="distance">Distance</label>
            <input class="usr__input" type="text" name="" id="distance" placeholder="km">
            <label for="duration">Duration</label>
            <input class="usr__input" type="text" name="" id="duration" placeholder="min">
            <label for="elev__cad" id="cadlbl">Cadence</label>
            <label for="elev__cad" id = "elevlbl">Elev Gain</label>
            <input class="usr__input" type="text" name="" id="elev__cad" placeholder="step/min">
            <!-- <input style="display: none;" class="usr__input" type="text" name="" id="cadence" placeholder="step/meter"> -->

        </form>
    </div>
</body>

js part:

class test{
  constructor(){
    document.querySelector('.input__form').addEventListener('submit', function(e){e.preventDefault();  console.log('inside form submit handler'); });
    document.querySelector(".input__div").addEventListener("keydown", ()=> console.log('inside keyboard handler'));
  }
}

new test();

and if you run the code you will see that it seems the submit form event listener never executed, as only the 'inside keyboard handler' would be printed on the console every time!!

pilchard
  • 12,414
  • 5
  • 11
  • 23
Blue
  • 43
  • 5
  • @pilchard yes, I write an event handler for both events and it seems like even though submit event happens and make page reload, but it's event handler function did not execute! But key event handler executed properly. Actually I wonder if submit event happened at all, why it's handler never run, and if it does not trigger, why page reloaded! – Blue Oct 17 '21 at 14:53
  • Intuitively, keydown must happen first. I suspect the overall order is `keydown`, `keyup`, `keypress`, `submit` (but I'm not sure what keypress does, so this part is a guess). – Cat Oct 17 '21 at 15:02
  • 1
    You'll note that the keydown is handled first in your test (if you add a submit button). This makes sense otherwise there would be no way to detect the 'enter' press. see: [DOM event precedence](https://stackoverflow.com/questions/282245/dom-event-precedence) and [Are event handlers in JavaScript called in order?](https://stackoverflow.com/questions/2706109/are-event-handlers-in-javascript-called-in-order) – pilchard Oct 17 '21 at 20:50

0 Answers0