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

Solution 1:

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.

Solution 2:

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.

Solution 3:

try this way:

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

Solution 4:

This other stackoverflow question should get you where you want:

$('#DialogTag').keyup(function(e) {
    if (e.keyCode == 13) {
        //Close dialog and/or submit here...
    }
});

Solution 5:

Another option that gives you more control over all buttons in the dialog is to add them as an array of buttons. Then in the open event you can get the buttons by id and do whatever you want (including set the focus)

$('#myDialog').dialog({
    buttons: [  
                {
                    id: "btnCancel",
                    text: "Cancel",
                    click: function(){
                        $(this).dialog('close');
                    }
                },
                {
                    id: "btnOne",
                    text: "Print One",
                    click: function () {
                        SomeFunction(1);
                    }
                },
                {
                    id: "btnTwo",
                    text: "Print Two",
                    click: function(){
                        SomeFunction(0);
                    }
                }
            ],
    open: function () {
        if ($('#hiddenBool').val() != 'True') {
            $('#btnOne').hide();
        }
        $("#btnTwo").focus();
    }
});