Robert MacLean
Robert MacLean

Reputation: 39261

jQuery UI Dialog + ASP.NET textboxes + focus

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

Upvotes: 5

Views: 15033

Answers (4)

Kunal Mukherjee
Kunal Mukherjee

Reputation:

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.

Upvotes: 7

brianpeiris
brianpeiris

Reputation: 10795

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

Upvotes: 4

alex
alex

Reputation:

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.

Upvotes: 1

Shaun Humphries
Shaun Humphries

Reputation: 1035

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

Upvotes: 3

Related Questions