Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery-ui Dialog: Make a button in the dialog the default action (Enter key)

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.

like image 289
fgui Avatar asked Mar 26 '10 09:03

fgui


4 Answers

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.

like image 148
Nick Craver Avatar answered Nov 11 '22 12:11

Nick Craver


I like this one (it is working for me), which leaves the focus where I wanted to be (a text box)

    $("#logonDialog").keydown(function (event) {
        if (event.keyCode == $.ui.keyCode.ENTER) {
            $(this).parent()
                   .find("button:eq(0)").trigger("click");
            return false;
        }
    });

However, this is working just for one button (Ok button), if needed ':eq(n)' could be set to select other button.

Note: I added a new line returning false to prevent event bubbling when the enter key is handled, I hope it helps better than before.

like image 33
Eugenio Miró Avatar answered Nov 11 '22 11:11

Eugenio Miró


try this way:

$("#myDialog").dialog({
    open: function() {
         $(this).siblings('.ui-dialog-buttonpane').find('button:eq(1)').focus(); 
    }
});
like image 20
madeuz Avatar answered Nov 11 '22 12:11

madeuz


This other stackoverflow question should get you where you want:

$('#DialogTag').keyup(function(e) {
    if (e.keyCode == 13) {
        //Close dialog and/or submit here...
    }
});
like image 12
Thomas Avatar answered Nov 11 '22 11:11

Thomas