This question is posted quite a bit and nobody seems to be able to provide a good solution that won’t behave questionably. So here’s my take on it…
$('<div id="myDialog"></div>').appendTo('body').dialog({
autoOpen: false,
modal: true,
closeOnEscape: true,
buttons: {
OK: function() {
$.ajax({
type: 'POST',
url: 'save.php',
data: $('#myDialog :input').serialize(),
error: function(xml, status, error) {
$('#myDialog').html('<p><strong>Error Code:</strong> '+status+'</p><p><strong>Explanation:</strong> '+error+'</p>');
}
});
},
Cancel: function() {
$(this).dialog('close');
}
},
open: function() {
$(this).html('').load('form.php');
},
focus: function() {
$(':input', this).keyup(function(event) {
if (event.keyCode == 13) {
$('.ui-dialog-buttonpane button:first').click();
}
});
}
});
Note: You can also trigger the event on any element (not just form fields) by using $(this) as the selector.
That’s it, enjoy 🙂