[jquery] 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 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!

This question is related to jquery html focus setfocus

The answer is


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.


$(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.


$("#header").attr('tabindex', -1).focus();

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.


As Omu pointed out, you must set the focus in a document ready function. jQuery provides it for you. And do select on an id. For example, if you have a login page:

$(function() { $("#login-user-name").focus(); }); // jQuery rocks!

$("#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


This runs on page load.

<script type="text/javascript">
    $(function () {
        $("#header").focus();
    });
</script>

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 - a callback.

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.


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.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to focus

How to remove focus from input field in jQuery? Set element focus in angular way Bootstrap button - remove outline on Chrome OS X How can I set focus on an element in an HTML form using JavaScript? Set Focus on EditText Mobile Safari: Javascript focus() method on inputfield only works with click? Correct way to focus an element in Selenium WebDriver using Java Prevent the keyboard from displaying on activity start What are some reasons for jquery .focus() not working? How can I set the focus (and display the keyboard) on my EditText programmatically

Examples related to setfocus

Set element focus in angular way Correct way to focus an element in Selenium WebDriver using Java How to Set Focus on JTextField? how to put focus on TextBox when the form load? Set focus to field in dynamically loaded DIV Setting focus to iframe contents