slolife slolife - 1 year ago 142
jQuery Question

Prevent jQuery UI dialog from setting focus to first textbox

I have setup a jQuery UI modal dialog to display when a user clicks a link. There are two textboxes (I only show the code for 1 for brevity) in that dialog div tag and it is changed to be a jQuery UI DatePicker textbox that reacts on focus.

The problem is that the jQuery UI dialog('open') somehow triggers the first textbox to have focus, which then triggers the datepicker calendar to open immediately.

So I am looking for a way to prevent the focus from happening automatically.

<div><a id="lnkAddReservation" href="#">Add reservation</a></div>

<div id="divNewReservation" style="display:none" title="Add reservation">
<th><asp:Label AssociatedControlID="txtStartDate" runat="server" Text="Start date" /></th>
<asp:TextBox ID="txtStartDate" runat="server" CssClass="datepicker" />

<asp:Button ID="btnAddReservation" runat="server" OnClick="btnAddReservation_Click" Text="Add reservation" />

<script type="text/javascript">
$(document).ready(function() {
var dlg = $('#divNewReservation');
$('.datepicker').datepicker({ duration: '' });
dlg.dialog({ autoOpen:false, modal: true, width:400 });
$('#lnkAddReservation').click(function() { dlg.dialog('open'); return false; });

Answer Source

jQuery UI 1.10.0 Changelog lists ticket 4731 as being fixed.

Looks like focusSelector was not implemented, but a cascading search for various elements was used instead. From the ticket:

Extend autofocus, starting with [autofocus], then :tabbable content, then buttonpane, then close button, then dialog

So, mark an element with the autofocus attribute and that is the element that should get the focus:

<input autofocus>

In the documentation, the focus logic is explained (just under the table of contents, under the title 'Focus'):

Upon opening a dialog, focus is automatically moved to the first item that matches the following:

  1. The first element within the dialog with the autofocus attribute
  2. The first :tabbable element within the dialog's content
  3. The first :tabbable element within the dialog's buttonpane
  4. The dialog's close button
  5. The dialog itself