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 in
This runs on page load.
<script type="text/javascript">
$(function () {
$("#header").focus();
});
</script>
$(function (){
$('body').on('keypress','.sobitie_snses input',function(e){
if(e.keyCode==13){
$(this).blur();
var new_fild = $(this).clone().val('');
$(this).parent().append(new_fild);
$(new_fild).focus();
}
});
});
most of error are because U use wrong object to set the prorepty or function. Use console.log(new_fild); to see to what object U try to set the prorepty or function.
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:
$( '#header' ).focus();
or the tempting:
setTimeout( $( '#header' ).focus(), 500 );
Try this:
setTimeout( function() { $( '#header' ).focus() }, 500 );
In my code, testing passing the argument, this didn't work, the timeout was ignored:
setTimeout( alert( 'Hello, '+name ), 1000 );
This works, the timeout ticks:
setTimeout( function() { alert( 'Hello, '+name ) }, 1000 );
It sucks that w3schools doesn't mention it.
Credits go to: makemineatriple.com.
Hopefully, this helps somebody who comes here.
Martas
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.