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
I know this is an old thread, but I was searching for this exact functionality and was able to implement what I think is the best solution as I found all of the above to fall short a little.
It is a combination of two answers above. Using an ID rather than relying on the find() function to find the button element always seems to be a much better choice to me.
Also explicitly looking for the enter key to be pressed allows us to set focus to whatever element we want when the dialog is opened if desired. This just seems to allow for the most flexibility while satisfying the desire of triggering a specific button as 'default' when the enter key is pressed. I have also implemented a 'cancel' default as well.
I hope this helps others looking for a good 'default' button solution for dialogs.
$("#LoginBox").dialog({
open: function(){
$(this).keydown(function (event) {
if (event.keyCode == 13) {
$("#LogInButton").trigger("click");
return false;
}
if (event.keyCode == 27) {
$("#CancelButton").trigger("click");
return false;
}
});
},
close: function(){
$(this).dialog("destroy");
},
buttons: [
{
id: "LogInButton",
text: "Log In",
click: function(){
//button functionality goes here
$(this).dialog("destroy");
}
},
{
id: "CancelButton",
text: "Cancel",
click: function(){
$(this).dialog("destroy");
}
}
]
});