views:

4936

answers:

4

Problem

I am using jQuery UI dialog to show a dialog box with some ASP.NET textboxes and a button in it. However as jQuery moves the div for the dialog box outside the form I need to re-move it back to the form myself (see this for details why), so that ASP.NET still works. This moving is causing a problem, where the field does not get focus if called.

If you look at the sample below the line labeled Line B should set the focus, however the line labeled line A breaks that. If I comment out line A it works. No matter where I move line B to (before dialog, line A etc...) it still fails to set focus.

By setting focus I mean the cursor is in the text box flashing ready to type.

Question how do I set the focus in this scenario?

Samples

HTML body sample

<body>
<form id="form1" runat="server">
<div id="popup">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</div>
</form>
</body>

jQuery sample

        $(document).ready(function() {
        var dlg = $("#popup").dialog();
        /*Line A*/ dlg.parent().appendTo(jQuery("form:first"));
        /*Line B*/ $("#TextBox2").focus();
    });
+2  A: 

It works in FF but not in IE7. I have figured out 2 work arounds. If you don't reference the textbox by name but by position, or for some reason if you set the focus twice.

The first:

$("input:text:second").focus();

The second:

$("#TextBox2").focus().focus();
Shaun Humphries
+1  A: 

you could also class the text box, as asp.net mangles control ids to avoid naming conflicts.

$(".mytextbox").focus();

as an example.. this of course defeats the purpose of semantics but semantics dont mix well with webforms.

+1  A: 

I think the problem is that you are moving the popup and calling focus before the dialog is fully created.

Try using the dialog's open event instead:

$(document).ready(function() {
  $("#popup").dialog({
    open: function(){
      $(this).parent().appendTo(jQuery("form:first"));
      $("#TextBox2").focus();
    }
  });
});
brianpeiris
+4  A: 

Try using setTimeout("$('#TextBox2').focus();",100);, for dialog and other methods of the jQuery UI sometimes it take few seconds to actually perform the tasks we assign by code.

Hope this helps. This workaround has helped in many of my applications.

Worked, but had to up my timeout to 500. Thx
theschmitzer