jquery-ui Dialog: Make a button in the dialog the

2019-01-13 04:27发布

In a jquery modal dialog, is there a way to select a button as the default action (action to execute when the user presses enter)?

Example of jquery web site: jquery dialog modal message

In the example above the dialog closes when the user presses Esc. I would like the "Ok" button action to be called when the user presses Enter.

14条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-13 04:32

This worked for me within the dialog using jquery 1.10.2

dialog({
    focus: function() {
        $(this).on("keyup", function(e) {
            if (e.keyCode === 13) {
                $(this).parent().find("button:eq(1)").trigger("click");
                return false;
            }
        });
    },

more options...

查看更多
女痞
3楼-- · 2019-01-13 04:32

You should to use :tabbable selector and index of your button (0 is [X] button, yours started from 1)

open: function() {
    var tb = $(":tabbable", this.parentNode);
    if(tb.length>1) {
        tb[1].focus();
    }
}
查看更多
对你真心纯属浪费
4楼-- · 2019-01-13 04:36

try this way:

$("#myDialog").dialog({
    open: function() {
         $(this).siblings('.ui-dialog-buttonpane').find('button:eq(1)').focus(); 
    }
});
查看更多
我想做一个坏孩纸
5楼-- · 2019-01-13 04:36

I'm using version 1.10.0. I could not get it to work with open but with focus. This focuses the second button:

focus: function(){
  $(this).siblings('.ui-dialog-buttonpane').find('button:eq(1)').focus();
}
查看更多
叼着烟拽天下
6楼-- · 2019-01-13 04:37

I like this one (it is working for me), which leaves the focus where I wanted to be (a text box)

    $("#logonDialog").keydown(function (event) {
        if (event.keyCode == $.ui.keyCode.ENTER) {
            $(this).parent()
                   .find("button:eq(0)").trigger("click");
            return false;
        }
    });

However, this is working just for one button (Ok button), if needed ':eq(n)' could be set to select other button.

Note: I added a new line returning false to prevent event bubbling when the enter key is handled, I hope it helps better than before.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-13 04:37

This simple piece of code styles your buttons and sets the default to the last one:

 open: function(){

      $buttonPane = $(this).next();
      $buttonPane.find('button:first').addClass('accept').addClass('ui-priority-secondary');
      $buttonPane.find('button:last').addClass('cancel').addClass('ui-state-default');
      $buttonPane.find('button:last').focus();

  },
查看更多
登录 后发表回答