Submit jQuery UI dialog on <Enter>

JavascriptJqueryJquery Ui

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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");
      }
    });
  };
});

Solution 2 - Javascript

I have summed up the answers above & added important stuff

$(document).delegate('.ui-dialog', 'keyup', function(e) {
        var target = e.target;
        var tagName = target.tagName.toLowerCase();
        
        tagName = (tagName === 'input' && target.type === 'button') 
          ? 'button' 
          : tagName;

        isClickableTag = tagName !== 'textarea' && 
          tagName !== 'select' && 
          tagName !== 'button';
        
        if (e.which === $.ui.keyCode.ENTER && isClickableTag) {
            $(this).find('.ui-dialog-buttonset button').eq(0).trigger('click');
            
            return false;
        }
    });

Advantages:

  1. Disallow enter key on non compatible elements like textarea , select , button or inputs with type button , imagine user clicking enter on textarea and get the form submitted instead of getting new line!
  2. The binding is done once , avoid using the dialog 'open' callback to bind enter key to avoid binding the same function again and again each time the dialog is 'open'ed
  3. Avoid changing existing code as some answers above suggest
  4. Use 'delegate' instead of the deprecated 'live' & avoid using the new 'on' method to allow working with older versions of jquery
  5. Because we use delegate , that mean the code above can be written even before initializing dialog. you can also put it in head tag even without $(document).ready
  6. Also delegate will bind only one handler to document and will not bind handler to each dialog as in some code above , for more efficiency
  7. Works even with dynamically generated dialogs like $('<div><input type="text"/></div>').dialog({buttons: .});
  8. Worked with ie 7/8/9!
  9. Avoid using the slow selector :first
  10. Avoid using hacks like in answers here to make a hidden submit button

Disadvantages:

  1. Run the first button as the default one , you can choose another button with eq() or call a function inside the if statement
  2. All of dialogs will have same behavior you can filter it by making your selector more specific ie '#dialog' instead of '.ui-dialog'

I know the question is old but I have had the same need, so, I shared the solution I've used.

Solution 3 - Javascript

$('#dialogBox').dialog('open');
$('.ui-dialog-buttonpane > button:last').focus();

It works beautifully with the latest version of JQuery UI (1.8.1). You may also use :first instead of :last depending on which button you want to set as the default.

This solution, compared to the selected one above, has the advantage of showing which button is the default one for the user. The user can also TAB between buttons and pressing ENTER will click the button currently under focus.

Cheers.

Solution 4 - Javascript

Ben Clayton's is the neatest and shortest and it can be placed at the top of your index page before any jquery dialogs have been initialized. However, i'd like to point out that ".live" has been deprecated. The preferred action is now ".on". If you want ".on" to function like ".live", you'll have to use delegated events to attach the event handler. Also, a few other things...

  1. I prefer to use the ui.keycode.ENTER method to test for the enter key since you don't have to remember the actual key code.

  2. Using "$('.ui-dialog-buttonpane button:first', $(this))" for the click selector makes the whole method generic.

  3. You want to add "return false;" to prevent default and stop propagation.

In this case...

$('body').on('keypress', '.ui-dialog', function(event) { 
    if (event.keyCode === $.ui.keyCode.ENTER) { 
        $('.ui-dialog-buttonpane button:first', $(this)).click();
        return false;
    }
});

Solution 5 - Javascript

A crude but effective way to make this work more generically:

$.fn.dlg = function(options) {
    return this.each(function() {
             $(this).dialog(options);
             $(this).keyup(function(e){
                  if (e.keyCode == 13) {				
                       $('.ui-dialog').find('button:first').trigger('click');
                  }
             });
    });
}

Then when you create a new dialog you can do this:

$('#a-dialog').mydlg({...options...})

And use it like a normal jquery dialog thereafter:

$('#a-dialog').dialog('close')

There are ways to improve that to make it work in more special cases. With the above code it will automatically pick the first button in the dialog as the button to trigger when enter is hit. Also it assumes that there is only one active dialog at any given time which may not be the case. But you get the idea.

Note: As mentioned above, the button that is pressed on enter is dependent on your setup. So, in some cases you would want to use the :first selector in .find method and in others you may want to use the :last selector.

Solution 6 - Javascript

Rather than listening for key codes like in this answer (which I couldn't get to work) you can bind to the submit event of the form within the dialog and then do this:

$("#my_form").parents('.ui-dialog').first().find('.ui-button').first().click();

So, the whole thing would look like this

$("#my_form").dialog({
  open: function(){
    //Clear out any old bindings
    $("#my_form").unbind('submit');
    $("#my_form").submit(function(){
      //simulate click on create button
      $("#my_form").parents('.ui-dialog').first().find('.ui-button').first().click();
      return false;
    });
  },
  buttons: {
    'Create': function() {
      //Do something
    },
    'Cancel': function() {
      $(this).dialog('close');
    }
  }
});

Note that different browsers handle the enter key differently, and some do not always do a submit on enter.

Solution 7 - Javascript

I don't know about simpler, but ordinarily you would track which button has the current focus. If the focus is changed to a different control, then the "button focus" would remain on the button that had focus last. Ordinarily, the "button focus" would start on your default button. Tabbing to a different button would change the "button focus". You'd have to decide if navigating to a different form element would reset the "button focus" to the default button again. You'll also probably need some visual indicator other than the browser default to indicate the focused button as it loses the real focus in the window.

Once you have the button focus logic down and implemented, then I would probably add a key handler to the dialog itself and have it invoke the action associated with the currently "focused" button.

EDIT: I'm making the assumption that you want to be able hit enter anytime you are filling out form elements and have the "current" button action take precedence. If you only want this behavior when the button is actually focused, my answer is too complicated.

Solution 8 - Javascript

I found this solution, it work's on IE8, Chrome 23.0 and Firefox 16.0

It's based on Robert Schmidt comment.

$("#id_dialog").dialog({
    buttons: [{
        text: "Accept",
        click: function() {
            // My function
        },
        id: 'dialog_accept_button'
    }]
}).keyup(function(e) {
    if (e.keyCode == $.ui.keyCode.ENTER)
        $('#dialog_accept_button').click();
});

I hope it help anyone.

Solution 9 - Javascript

Sometimes we forget the fundamental of what the browser already supports:

<input type="submit" style="visibility:hidden" />

This will cause the ENTER key to submit the form.

Solution 10 - Javascript

I did such way... ;) Hope it will helpful for somebody..

$(window).keypress(function(e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        $(".ui-dialog:visible").find('.ui-dialog-buttonpane').find('button:first').click();
        return false;
    }
});

Solution 11 - Javascript

This should work to trigger the click of the button's click handler. this example assumes you have already set up the form in the dialog to use the jquery.validate plugin. but could be easily adapted.

open: function(e,ui) {
    $(this).keyup(function(e) {
        if (e.keyCode == 13) {
           $('.ui-dialog-buttonpane button:last').trigger('click');
		}
	});
},
buttons: {
    "Submit Form" : function() {
			var isValid = $('#yourFormsID').valid();
			// if valid do ajax call
			if(isValid){
               //do  your ajax call here. with serialize form or something...

            }
}

Solution 12 - Javascript

done and done

  $('#login input').keyup(function(e) {
      if (e.keyCode == 13) {
          $('#login form').submit();
      }
   }

Solution 13 - Javascript

I realise there are a lot of answers already, but I reckon naturally that my solution is the neatest, and possibly the shortest. It has the advantage that it works on any dialogs created any time in the future.

$(".ui-dialog").live("keyup", function(e) {
    if (e.keyCode === 13) {
        $('.ok-button', $(this) ).first().click();
    }
});

Solution 14 - Javascript

Here is what I did:

myForm.dialog({
  "ok": function(){
    ...blah...
  }
  Cancel: function(){
    ...blah...
  }
}).keyup(function(e){
  if( e.keyCode == 13 ){
   $(this).parent().find('button:nth-child(1)').trigger("click");
  }
});

In this case, myForm is a jQuery object containing the form's html (note, there aren't any "form" tags in there... if you put those in the whole screen will refresh when you press "enter").

Whenever the user presses "enter" from within the form it will be the equivalent of clicking the "ok" button.

This also avoids the issue of having the form open with the "ok" button already highlighted. While that would be good for forms with no fields, if you need the user to fill in stuff, then you probably want the first field to be highlighted.

Solution 15 - Javascript

if you know the button element selector :

$('#dialogBox').dialog('open');
$('#okButton').focus();

Should do the trick for you. This will focus the ok button, and enter will 'click' it, as you would expect. This is the same technique used in native UI dialogs.

Solution 16 - Javascript

   $("#LogOn").dialog({
       modal: true,
       autoOpen: false,
       title: 'Please Log On',
       width: 370,
       height: 260,
       buttons: { "Log On": function () { alert('Hello world'); } },
       open: function() { $(this).parents('.ui-dialog-buttonpane button:eq(0)').focus();}
   });

Solution 17 - Javascript

I found a quite simple solution for this problem:

var d = $('<div title="My dialog form"><input /></div>').dialog(
    buttons: [{
        text: "Ok",
        click: function(){
            // do something
            alert('it works');
        },
        className: 'dialog_default_button'
    }]
});

$(d).find('input').keypress(function(e){
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        e.preventDefault();
        $('.dialog_default_button').click();
    }
});

Solution 18 - Javascript

$('#DialogID').dialog("option", "buttons")["TheButton"].apply()

This worked great for me..

Solution 19 - Javascript

None of these solutions seemed to work for me in IE9. I ended up with this..

$('#my-dialog').dialog({
    ...
    open: function () {
        $(this).parent()
               .find("button:eq(0)")
               .focus()
               .keyup(function (e) {
                   if (e.keyCode == $.ui.keyCode.ENTER) {
                       $(this).trigger("click");
                   };
               });
    }
});

Solution 20 - Javascript

Below body is used because dialog DIV added on body,so body now listen the keyboard event. It tested on IE8,9,10, Mojila, Chrome.

open: function() {
$('body').keypress(function (e) { 
     if (e.keyCode == 13) {   
     $(this).parent().find(".ui-dialog-buttonpane button:eq(0)").trigger("click");
     return false; 
     }
  }); 
}

Solution 21 - Javascript

Because I don't have enough reputation to post comments.

$(document).delegate('.ui-dialog', 'keyup', function(e) {
  var tagName = e.target.tagName.toLowerCase();

  tagName = (tagName === 'input' && e.target.type === 'button') ? 'button' : tagName;

  if (e.which === $.ui.keyCode.ENTER && tagName !== 'textarea' && tagName !== 'select' && tagName !== 'button') {
      $(this).find('.ui-dialog-buttonset button').eq(0).trigger('click');
    return false;
  } else if (e.which === $.ui.keyCode.ESCAPE) {
      $(this).close();
  }
});

Modified answer by Basemm #35 too add in Escape to close the dialog.

Solution 22 - Javascript

It works fine Thank You!!!

open: function () { debugger; $("#dialogDiv").keypress(function (e) { if (e.keyCode == 13) { $(this).parent().find("#btnLoginSubmit").trigger("click"); } }); },

Solution 23 - Javascript

Give your buttons classes and select them the usual way:

$('#DialogTag').dialog({
  closeOnEscape: true,
  buttons: [
    {
      text: 'Cancel',
      class: 'myCancelButton',
      click: function() {
        // Close dialog fct
      }
    },
    {
      text: 'Ok',
      class: 'myOKButton',
      click: function() {
        // OK fct
      }
    }
  ],
  open: function() {

    $(document).keyup(function(event) {

      if (event.keyCode === 13) {
        $('.myOKButton').click();
      }
      
    });

  }
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCMBView Question on Stackoverflow
Solution 1 - JavascriptCasey WilliamsView Answer on Stackoverflow
Solution 2 - JavascriptBasemmView Answer on Stackoverflow
Solution 3 - JavascriptMario AwadView Answer on Stackoverflow
Solution 4 - JavascriptNelson MView Answer on Stackoverflow
Solution 5 - JavascriptKarimView Answer on Stackoverflow
Solution 6 - JavascriptSalida SoftwareView Answer on Stackoverflow
Solution 7 - JavascripttvanfossonView Answer on Stackoverflow
Solution 8 - JavascriptPablo OñaView Answer on Stackoverflow
Solution 9 - JavascriptSeifuView Answer on Stackoverflow
Solution 10 - JavascriptStanislav VychegzhaninView Answer on Stackoverflow
Solution 11 - JavascripttimbrownView Answer on Stackoverflow
Solution 12 - JavascriptkevinView Answer on Stackoverflow
Solution 13 - JavascriptBen ClaytonView Answer on Stackoverflow
Solution 14 - JavascriptTylerView Answer on Stackoverflow
Solution 15 - Javascriptsandesh247View Answer on Stackoverflow
Solution 16 - JavascriptLeCramView Answer on Stackoverflow
Solution 17 - JavascriptRobert SchmidtView Answer on Stackoverflow
Solution 18 - JavascriptPeterView Answer on Stackoverflow
Solution 19 - JavascriptPaul MartinView Answer on Stackoverflow
Solution 20 - JavascriptLoopCoderView Answer on Stackoverflow
Solution 21 - JavascriptLiam MitchellView Answer on Stackoverflow
Solution 22 - JavascriptDurgaprasad KatariView Answer on Stackoverflow
Solution 23 - JavascriptyPhilView Answer on Stackoverflow