绑定输入jquery ui对话框按钮的键

时间:2013-02-14 12:01:49

标签: jquery jquery-ui

我的jquery对话框上有两个按钮确定并取消。我希望当用户在当前打开的Jquery ui对话框上按Enter键时,它会像点击Ok一样。按钮的定义如下:

     $("#dialog-confirm").dialog({
                    autoOpen: true,
                    resizable: true,
                    modal: true,
                    width: 458,
                    Height: 184,

                    buttons: {
                        "Login": function () {
                            $(this).dialog("close");  
 $("#frmsetAccount").submit();                        
                        },
                        "Cancel": function () {
                            $(this).dialog("close");                           

                        }
                    }
                });
    });

请建议解决方案

3 个答案:

答案 0 :(得分:2)

您可以使用KeyPress或KeyUp事件

$('#targetElement').on('keypress', function(e) {
 var code = (e.keyCode ? e.keyCode : e.which);
 if(code == 13) { //Enter keycode
   //close your dialog box. -make sure you get the dialog object first. then close it. or call some function which is in ok button. 
 }
});

KEYUP

$('#targetElement').keyup(function(e) {
     var code = (e.keyCode ? e.keyCode : e.which);
     if(code == 13) { //Enter keycode
       //Do something
     }
    });

答案 1 :(得分:2)

我发现这篇文章已经过时了,但这些回复并没有真正回答这个问题。如果正确设置对话框,则将热键事件添加到jQuery对话框很简单。我在下面写了一些代码,这些代码对于大多数用例都是通用的。

您可以在以下位置查看工作副本 https://jsfiddle.net/bsalines/xpvt214o/3180/

$('<div id="yourJqueryDialogId"></div>').appendTo('body')
    .html(html) //add your custom html to be displayed in dialog
    .dialog({
        modal: true,
        title: 'Some Title',
        autoOpen: true,
        width: 500,
        height: 450,
        resizable: false,
        draggable: false,

        buttons: {
            Cancel: {
                text: "Cancel",
                class: "model-cancel",
                click: function() {
                    // Add your code if you want to do something on close/cancel/exit
                    $(this).dialog("close");
                    $(this).dialog('destroy').remove();
                }
            },
            Save: {
                text: "Update",
                class: "model-update",
                id: "yourJqueryButtonId", // id for hotkey
                click: function() {
                    //Add your code here for hotkey and update/save/submit
                    $(this).dialog("close");
                    $(this).dialog('destroy').remove();

                },

            },
        }
    });

$("#yourJqueryDialogId").keydown(function(e) { if(e.which == 13) {
    $('#yourJqueryButtonId').click();
           return false;
      } });

答案 2 :(得分:0)

只需使用keyup

$(document).keyup(function(e) {
    if (e.keyCode == 13) // close the dialog
});