jQuery dynamic input field focus

Kumite picture Kumite · Oct 25, 2012 · Viewed 17.8k times · Source

I want to add an input field dynamically to my page using the following jQuery:

var inputNode = "<input id='inputNode' class='tiContent' type='text'
    placeholder='text input...'/>";
$("div").append(inputNode);

and after doing so, I want the input field to have focus with blinking text cursor, so I want to type in it right after creation.

Could someone please tell me how can I do this?

I've tried calling

$(inputNode).focus()

and also have tried

$(inputNode).trigger('click')

but none of them worked. I can type into the field after clicking in it, but as I've said I want to type without any interaction immediately.

Answer

andyb picture andyb · Oct 25, 2012

When you tried $(inputNode).focus(), jQuery was simply building a new disconnected (from the DOM) <input> element which was different to the one you had appended - although this disconnected one was focussed :-)

There are a couple of ways to focus the input.

If you can use HTML5 then adding the autofocus attribute will focus the input

var inputNode = '<input autofocus id="inputNode" class="tiContent" type="text" placeholder="text input..."/>';
$('div').append(inputNode);

Or, using jQuery, you need to find the <input> after the element has been created to call .focus() on it, as the inputNode in your code is simply a string and not a jQuery object.

var inputNode = '<input id="inputNode" class="tiContent" type="text" placeholder="text input..."/>';
$('div').append(inputNode);
$('div input').focus(); // or $('#inputNode').focus();