Cannot set focus to a form field in a jQuery UI dialog on clicking a jQueryUI menu item

北战南征 提交于 2019-12-07 05:02:37

问题


I've got a jQuery UI dialog containing a one-field form and the autoOpen property is set to false at the beginning. There's another jQuery UI menu on the page and the dialog's open function is binding to the click event of the menu items. I've been trying to set focus to the only form field of the dialog when the dialog is open on click of the menu items somehow no luck. To pinpoint the cause I also added another test button and by clicking that button I can set focus to the form field. So I'm pretty sure it's the jQuery UI menu that is preventing the focus of the field. I wonder if there's any way that I can circumvent this constraint. Any insight is appreciated. Thanks!

html:

<ul id="menu">
    <li><a href="#">Item 1</a></li>
    <li><a href="#">Item 2</a></li>
</ul>
</br>
<button id="btn">Open the dialog</button>

<div id="dialog" title="Basic dialog">
    <form>
        <input type="text" id="fld" />
    </form>
</div>

javascript:

$( "#dialog" ).dialog({
    autoOpen: false,
    open: function(event, ui){
        $('#fld').focus();
    }
});

$('#btn').click(function(e){
    $( "#dialog" ).dialog('open');
});

$('#menu li a').click(function(){
    $( "#dialog" ).dialog('open');
})

$( "#menu" ).menu({
    select: function( event, ui ) {
        $( "#dialog" ).dialog('open');
    }
});

Here is the js fiddle


回答1:


Interesting.

jQuery's menu is affecting the on focus somehow. I was looking into your fiddle and I found that even if you delay the focus 1 millisecond it works.

Take a look at this.

$( "#dialog" ).dialog({
   autoOpen: false,
   open: function(event, ui){
       setTimeout(function(){$('#fld').focus();},1);
   }
});

$('#btn').click(function(e){
   $( "#dialog" ).dialog('open');
});

$('#menu li a').click(function(){
   $( "#dialog" ).dialog('open');
})

$( "#menu" ).menu();

http://jsfiddle.net/XMEWu/1/




回答2:


This one drove me mad. Here's what fixed it for me (more generic version of @Trevor's answer).

$('#element').dialog({
  open: function () {                        
    //focus fix
    $('textarea, input', $(this)).click(function() {
        var $inp = $(this);
        setTimeout(function () {
            $inp.focus();
        }, 1);
    });                        
  }
});



回答3:


Use on Dialog Page

$(window).load(function() {
   //Use Focus as $("#stsr").focus();
}


来源:https://stackoverflow.com/questions/19125813/cannot-set-focus-to-a-form-field-in-a-jquery-ui-dialog-on-clicking-a-jqueryui-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!