Search code examples
javascriptjqueryformsjquery-dialog

jQuery dialog Enter to submit (without form focus)


Background

Using a jQuery modal dialog to present a form. The form has an autocomplete field. When the user selects an option from the autocomplete drop-down, the form loses focus. The jQuery dialog detects the ESC key, however ENTER key is never detected. Consider one of several forms (on the same page), having a variety of buttons:

Code

The source code to detect when the ENTER key is pressed:

  $(form).keyup(function( e ) {
    // Submit and close when Enter key pressed by triggering the accept button.
    //
    if( e.keyCode == $.ui.keyCode.ENTER ) {
      sequenceNumber = 0;
      $(this).parent().find( "#accept" ).trigger( 'click' );
    }
  });

This works as expected (the "accept" button is triggered and the server receives the values just fine) whenever any field of the form has focus.

Problem

When the dialog is shown but no fields have focus (e.g., the user clicks on "fish fillet" in the above image), then presses ENTER, the keyup event is never fired.

Question

How can you receive an ENTER event when the form does not have focus, but the jQuery dialog is still open? (In the same way that the jQuery dialog receives the ESC keypress to cancel and close the dialog.)

Thank you!


Solution

  • I added the trigger on the body instead, then I check if the form is visible.

    $('body').keyup(function( e ) {
      if( e.keyCode == $.ui.keyCode.ENTER ) {
        if( $("#myform").is(":visible") ) {
          // Enter was pressed and form is visible
        }
      }
    });