Prevent users from submitting a form by hitting Enter

后端 未结 30 3554
感动是毒
感动是毒 2020-11-21 05:13

I have a survey on a website, and there seems to be some issues with the users hitting enter (I don\'t know why) and accidentally submitting the survey (form) without clicki

30条回答
  •  失恋的感觉
    2020-11-21 05:53

    There are many good answers here already, I just want to contribute something from a UX perspective. Keyboard controls in forms are very important.

    The question is how to disable from submission on keypress Enter. Not how to ignore Enter in an entire application. So consider attaching the handler to a form element, not the window.

    Disabling Enter for form submission should still allow the following:

    1. Form submission via Enter when submit button is focused.
    2. Form submission when all fields are populated.
    3. Interaction with non-submit buttons via Enter.

    This is just boilerplate but it follows all three conditions.

    $('form').on('keypress', function(e) {
      // Register keypress on buttons.
      $attr = $(e.target).attr('type);
      if ($attr === 'button' || $attr === 'submit') {
        return true;
      }
    
      // Ignore keypress if all fields are not populated.
      if (e.which === 13 && !fieldsArePopulated(this)) {
        return false;
      }
    });

提交回复
热议问题