Tutorial :jQuery UI Dialog + ASP.NET textboxes + focus



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?


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();      });  


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:


The second:



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.


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();      }    });  });  


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


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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »