Prevent users from submitting a form by hitting Enter

后端 未结 30 3541
感动是毒
感动是毒 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:55

    I needed to prevent only specific inputs from submitting, so I used a class selector, to let this be a "global" feature wherever I need it.

    
    

    And this jQuery code:

    $('.idNoEnter').keydown(function (e) {
      if (e.keyCode == 13) {
        e.preventDefault();
      }
    });
    

    Alternatively, if keydown is insufficient:

    $('.idNoEnter').on('keypress keydown keyup', function (e) {
       if (e.keyCode == 13) {
         e.preventDefault();
       }
    });
    

    Some notes:

    Modifying various good answers here, the Enter key seems to work for keydown on all the browsers. For the alternative, I updated bind() to the on() method.

    I'm a big fan of class selectors, weighing all the pros and cons and performance discussions. My naming convention is 'idSomething' to indicate jQuery is using it as an id, to separate it from CSS styling.

提交回复
热议问题