The simplest way would be to use the submit action on a form within the dialog, however:
- I did not want to require a form within dialog (N.B. different browsers handle the enter key differently, and some do not always do a submit on enter).
- I wanted this to work if the user clicks in the title pane or button pane prior to pressing enter.
- I wanted to make a library method that I can use for ANY
jQueryUI dialog.
The company I work for is 'EBL' and I avoid global scope...hence the prefix on the functions below:
EBL.onUiDialogOpen = function (event, ui, hideX, actionFirstButtonOnEnterKey) {
if (hideX) {
// There is no option to hide the 'X' so override.
$(".ui-dialog-titlebar-close").hide();
}
if (actionFirstButtonOnEnterKey) {
/* (event.target) will give the div that will become the content
of a UI dialog, once div is 'opened' is it surrounded by a
parent div that contains title and buttonpane divs as well as
content div - so I use .parent()
...The keyup function is binded to all descendants, therefore:
-We need the e.stopPropagation() line.
-This code is NOT what you want if you DON'T want enter
key to initiate first button regardless of selected control.
*/
$(event.target).parent().bind('keydown.justWhileOpen', function (e) {
if (e.keyCode === $.ui.keyCode.ENTER) {
e.stopPropagation();
$(event.target).next('.ui-dialog-buttonpane')
.find('button:first').click();
}
});
}
};
...works in combination with:
EBL.onUiDialogClose = function (event, ui) {
// Remove keyup handler when we close dialog
$(event.target).parent().unbind('.justWhileOpen');
};
You do not need the .onUiDialogClose if you are using a dynamically created div and destroying it afterwards.
You can see below how I use these library functions when initialising a non-dynamic dialog...
$('#divName').dialog({
//...
open: function (event, ui) { EBL.onUiDialogOpen(event, ui, false, true); },
close: function (event, ui) { EBL.onUiDialogClose(event, ui); },
//...
});
So far I have tested this in IE9 and latest chrome/firefox.
You should validate the dialog as neccessary in your 'Ok' function.