MrG MrG - 4 months ago 23
jQuery Question

Set focus to field in dynamically loaded DIV

What is the proper method to set the focus to a specific field within a dynamically loaded DIV?

$("#display").load("?control=msgs"); // loads the HTML into the DIV
$('#display').fadeIn("fast"); // display it
$("tex#header").focus(); // ?? neither that
$("input#header").focus(); // ?? nor that
$('#display', '#header').focus() // ?? nor that
$("#header").focus(); // ?? nor that works

The following HTML is fetched into the

<div id="display">
<form id="newHeaderForm" class="dataform" action="/" method="post">
<input id="to" type="hidden" value="22" name="to"/>
<input id="header" class="large" type="text" name="header" value="" maxlength="128"/>

Many, many thanks!


The load() function is an asynchronous function. You should set the focus after the load() call finishes, that is in the callback function of load(), because otherwise the element you are referring to by #header, does not yet exist. For example:

$("#display").load("?control=msgs", {}, function() { 

I had issues myself even with this solution, so i did a setTimeout in the callback and set the focus in the timeout to make /really/ sure the element exists.