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!
i tried it but it doesn't work, please give me more advice to resolve this problem. thanks for your help
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:
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.
This runs on page load.
Yes, this happens when manipulating an element which doesn't exist yet (a few contributors here also made a good point with the unique ID). I ran into a similar issue. I also need to pass an argument to the function manipulating the element soon to be rendered.
The solution checked off here didn't help me. Finally I found one that worked right out of the box. And it's very pretty, too - closures.
Instead of:
Try this:
In my code, testing passing the argument, this didn't work, the timeout was ignored:
This works, the timeout ticks:
It sucks that w3schools doesn't mention it.
Credits go to: makemineatriple.com.
Hopefully, this helps somebody who comes here.
Martas