Bijumon Attipil
Bijumon Attipil

Reputation: 41

focus an element created on the fly

how to focus an element created on the fly?

Upvotes: 4

Views: 6078

Answers (5)

Murat Tutumlu
Murat Tutumlu

Reputation: 780

<script>    
  $('#container').append('<input type="text">');
  $('#container').find('input:last').focus();
</script>

Upvotes: 0

notnotundefined
notnotundefined

Reputation: 3751

You can use setTImeOut

setTimeout(function() {
        $("#id_of_element_created").focus().select();
       }, 100);

Upvotes: -2

Chinmayee G
Chinmayee G

Reputation: 8117

Try this code,

var txtObj = document.createElement("input");
window.document.body.appendChild(a);
txtObj.focus();

Upvotes: 0

Andrzej Doyle
Andrzej Doyle

Reputation: 103797

The focus method will do this. If you have a reference to the newly-created element called elem, then simply invoke:

elem.focus();

Note that you'll need to do this after inserting the element into the document at the appropriate point, of course.

Upvotes: 4

Nick Craver
Nick Craver

Reputation: 630429

Just call .focus() on the element after it's added to the DOM, for example:

var input = document.createElement("input"); //create it
document.body.appendChild(input);            //append it
input.focus();                               //focus it

You can test it out here.

Upvotes: 8

Related Questions