Prevent form submission on Enter key press

前端 未结 19 2239
失恋的感觉
失恋的感觉 2020-11-22 04:18

I have a form with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want

19条回答
  •  不要未来只要你来
    2020-11-22 05:15

    Cross Browser Solution

    Some older browsers implemented keydown events in a non-standard way.

    KeyBoardEvent.key is the way it is supposed to be implemented in modern browsers.

    which and keyCode are deprecated nowadays, but it doesn't hurt to check for these events nonetheless so that the code works for users that still use older browsers like IE.

    The isKeyPressed function checks if the pressed key was enter and event.preventDefault() hinders the form from submitting.

      if (isKeyPressed(event, 'Enter', 13)) {
        event.preventDefault();
        console.log('enter was pressed and is prevented');
      }
    

    Minimal working example

    JS

    function isKeyPressed(event, expectedKey, expectedCode) {
      const code = event.which || event.keyCode;
    
      if (expectedKey === event.key || code === expectedCode) {
        return true;
      }
      return false;
    }
    
    document.getElementById('myInput').addEventListener('keydown', function(event) {
      if (isKeyPressed(event, 'Enter', 13)) {
        event.preventDefault();
        console.log('enter was pressed and is prevented');
      }
    });
    

    HTML

    https://jsfiddle.net/tobiobeck/z13dh5r2/

提交回复
热议问题