views:

496

answers:

2

In a jquery modal dialog, is there a way to select a button as the default action (action to execute when the user presses enter)?

Example of jquery web site: jquery dialog modal message

In the example above the dialog closes when the user presses Esc. I would like the "Ok" button action to be called when the user presses Enter.

+1  A: 

This other stackoverflow question should get you where you want:

$('#DialogTag').keyup(function(e) {
    if (e.keyCode == 13) {
        //Close dialog and/or submit here...
    }
});
Thomas
I did not found the question before posting this question. It is definely almost the same question. Thanks for pointing it out. I tried to make this code work without to much success. I tried downloading the latest version of jqueryui and adding this code to the example (index.html), I did not manage to make it work.
zesc
+3  A: 

In your dialog's open function, you can focus the button:

$("#myDialog").dialog({
    open: function() {
      $(this).parents('.ui-dialog-buttonpane button:eq(0)').focus(); 
    }
});

Change the :eq(0) if it's at a different index, or find by name, etc.

Nick Craver
I just wrote the code to using $(this).parent().find('button:nth-child(1)').focus(); which is similar. Thanks
zesc