Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 474
aarryy Avatar asked Oct 01 '13 20:10

aarryy


2 Answers

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/

like image 84
Trevor Avatar answered Nov 13 '22 10:11

Trevor


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);
    });                        
  }
});
like image 44
lamarant Avatar answered Nov 13 '22 12:11

lamarant