Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  45] [ 6]  / answers: 1 / hits: 91238  / 15 Years ago, fri, may 15, 2009, 12:00:00

I have a jQuery UI dialog box with a form. I would like to simulate a click on one of the dialog's buttons so you don't have to use the mouse or tab over to it. In other words, I want it to act like a regular GUI dialog box where simulates hitting the OK button.



I assume this might be a simple option with the dialog, but I can't find it in the jQuery UI documentation. I could bind each form input with keyup() but didn't know if there was a simpler/cleaner way. Thanks.


More From » jquery

 Answers
138

I don't know if there's an option in the jQuery UI widget, but you could simply bind the keypress event to the div that contains your dialog...



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


This'll run no matter what element has the focus in your dialog, which may or may not be a good thing depending on what you want.



If you want to make this the default functionality, you can add this piece of code:



// jqueryui defaults
$.extend($.ui.dialog.prototype.options, {
create: function() {
var $this = $(this);

// focus first button and bind enter to it
$this.parent().find('.ui-dialog-buttonpane button:first').focus();
$this.keypress(function(e) {
if( e.keyCode == $.ui.keyCode.ENTER ) {
$this.parent().find('.ui-dialog-buttonpane button:first').click();
return false;
}
});
}
});


Here's a more detailed view of what it would look like:



$( #dialog-form ).dialog({
buttons: { … },
open: function() {
$(#dialog-form).keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
$(this).parent().find(button:eq(0)).trigger(click);
}
});
};
});

[#99525] Tuesday, May 12, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ervindouglasm

Total Points: 451
Total Questions: 103
Total Answers: 102

Location: Turkmenistan
Member since Thu, Dec 1, 2022
2 Years ago
;