JQUERY - capture enter key press

How do i capture enter key press in the following?  
(what I'm trying to do is have it close the JQUERY UI dialog when the enter is pressed)

$("#dialog-save").dialog({
   autoOpen: false,
   modal: true,
   height: 185,
   width: 300,
   buttons: {
		Ok: function() {
			$( this ).dialog( "close" );
			location.reload(true);
		}
	}
});

Open in new window

LVL 3
EricLynnWrightAsked:
Who is Participating?
 
Julian HansenConnect With a Mentor Commented:
Try this - add this as an event handler - not in the button function above
$(function() {
  $(document).keypress(function() {
    $('#dialog-save").dialog("close");
  });
});

Open in new window

like this
$(function() {
 ...
  $(document).keypress(function() {
    $('#dialog-save").dialog("close");
  });

  $("#dialog-save").dialog({
    autoOpen: false,
    modal: true,
    height: 185,
    width: 300,
    buttons: {
		Ok: function() {
			$( this ).dialog( "close" );
			location.reload(true);
		}
	}
  });
});

Open in new window

0
 
EricLynnWrightAuthor Commented:
Thanks, julian.

However, it prevented the dialog from functioning.
0
 
EricLynnWrightAuthor Commented:
I was able to get this to work after seeing your suggestions.  
Thanks for the help!



$('body').keyup(function( e ) {
  if( e.keyCode == $.ui.keyCode.ENTER ) {
      if( $("#dialog-save").is(":visible") ) {
                        $("#dialog-save").dialog( "close" );
                        location.reload(true);
      }
  }
});
0
 
Julian HansenCommented:
Sorry missed that thought you said any key

here you go
$(function() {
 ...
  $(document).keypress(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
      if(code == 13) { //Enter keycode
        $('#dialog-save").dialog("close");
      }
  });

  $("#dialog-save").dialog({
    autoOpen: false,
    modal: true,
    height: 185,
    width: 300,
    buttons: {
		Ok: function() {
			$( this ).dialog( "close" );
			location.reload(true);
		}
	}
  });
});

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.