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.
In my case, none of the answers worked because I called
.dialog
on an empty div and added my buttons dynamically, so the$(this).html()
would return nothing. So I couldn't call methods likeparent()
orsiblings()
and expect something in return. What I did was select theui-dialog-buttonpane
class directly and find the button element from thereHTML
Jquery
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)
In your dialog's open function, you can focus the button:
Change the
:eq(0)
if it's at a different index, or find by name, etc.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.
A slight variation to use the buttons name as the selector. It reads a little better but there is obvious duplication with the button text string. Refactor to taste.
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:
...works in combination with:
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...
So far I have tested this in IE9 and latest chrome/firefox. You should validate the dialog as neccessary in your 'Ok' function.