views:

6603

answers:

6

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 display DIV:

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

Many, many thanks!

+3  A: 

Have you tried simply selecting by Id?

$("#header").focus();

Seeing as Ids should be unique, there's no need to have a more specific selector.

Paul Suart
Many thanks, but this doesn't work either ;(
MrG
you should have put this inside document.ready function
Omu
A: 

The HTML you are working with would be helpful.

Chris
This should be a comment.
Cory Larson
+1  A: 

If

$("#header").focus();

is not working then is there another element on your page with the id of header?

Use firebug to run $("#header") and see what it returns.

Bela
+5  A: 

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() { 
  $('#header').focus();
});

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.

Jan Willem B
A: 

Dynamically added items have to be added to the DOM... clone().append() adds it to the DOM... which allows it to be selected via jquery.

BCnuckles
+1  A: 
$("#display").load("?control=msgs", {}, function() { 
  $('#header').focus();
});

i tried it but it doesn't work, please give me more advice to resolve this problem. thanks for your help

xman
Did you set the ID of the field like <input id="header"..> ? Test your code in Firefox and enable the Error Console or in Chrome with a breakpoint at the right place, this might help.
MrG