Prevent form submission on Enter key press

前端 未结 19 1957
失恋的感觉
失恋的感觉 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:10

    A jQuery solution.

    I came here looking for a way to delay the form submission until after the blur event on the text input had been fired.

    $(selector).keyup(function(e){
      /*
       * Delay the enter key form submit till after the hidden
       * input is updated.
       */
    
      // No need to do anything if it's not the enter key
      // Also only e.which is needed as this is the jQuery event object.
      if (e.which !== 13) {
           return;
      }
    
      // Prevent form submit
      e.preventDefault();
    
      // Trigger the blur event.
      this.blur();
    
      // Submit the form.
      $(e.target).closest('form').submit();
    });
    

    Would be nice to get a more general version that fired all the delayed events rather than just the form submit.

提交回复
热议问题