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: jquer
try this way:
$("#myDialog").dialog({
open: function() {
$(this).siblings('.ui-dialog-buttonpane').find('button:eq(1)').focus();
}
});
You should to use :tabbable selector and index of your button (0 is [X] button, yours started from 1)
open: function() {
var tb = $(":tabbable", this.parentNode);
if(tb.length>1) {
tb[1].focus();
}
}
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.
The simplest way would be to use the submit action on a form within the dialog, however:
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.
This other stackoverflow question should get you where you want:
$('#DialogTag').keyup(function(e) {
if (e.keyCode == 13) {
//Close dialog and/or submit here...
}
});
I'm using version 1.10.0. I could not get it to work with open but with focus. This focuses the second button:
focus: function(){
$(this).siblings('.ui-dialog-buttonpane').find('button:eq(1)').focus();
}