views:

253

answers:

2

Hi - I'm trying to use jQuery's keypress to trigger a button click on a modal dialog created using the jQuery dialog function. The problem is, with the following code, it works the first time around (pressing enter presses the Save button) but I get erratic behavior when I close the modal dialog and reopen it. I'm thinking some variant of $(this).("button:contains('Save')") would work, but that doesn't work.

$('#dialog').keypress(function(e) {
        if (e.which == 13) {
      $("button:contains('Save')").click();
        }
});

FYI the dialog is opened using a $("#dialog").dialog('open'), not an autoOpen:true. What would be the best practice for the task?

Thanks!

+1  A: 

I would do:

$('#dialog').keyup(function(e) {
    if (e.which == 13) {
         var buttons = $(this).dialog('option', 'buttons');
         buttons['Save']();
         e.stopPropagation();
    }
})
Ken Browning
It seems to do the job for one dialog, but when "Save" opens a new dialog, everything closes .. the new dialog doesn't have another "Save" button, either...
Rio
The keyup event handler will not be detached from the element unless you remove the element from the DOM. Sounds like you have another problem somewhere else.
Ken Browning
+2  A: 

keypress is for letters. keydown is for everything. I would try using keydown.

Your code most likely does not execute. Enter will trigger the default action so that's why it works the first time.

More info here:

http://www.bloggingdeveloper.com/post/KeyPress-KeyDown-KeyUp-The-Difference-Between-Javascript-Key-Events.aspx

easement
Actually, you're partially right. If the dialog contains a form, pressing enter "submits" it, but Ken's response helps when the dialog doesn't contain a form, because then pressing enter doesn't do anything.
Rio