subharb
subharb

Reputation: 3472

Focus on an input after creating it

I would like to substitute a text input for a password input after clicking on the first one, my code creates it but it doesnt have focus on the new input, I would like to change this.

Here's my code.

$('.input_center input:text').click(function(){
var padre = $(this).parent();
                var passInput = $(document.createElement("div"));
                passInput.html('<input type="password">');
                padre.append(passInput);
                passInput.focus();
                $(this).remove();
});

That passInput.focus() is not doing the focus, so I dont know how to get it done.

Upvotes: 3

Views: 4952

Answers (2)

Jamie
Jamie

Reputation: 864

Try

var v = $('<div><input class="pwd" type="password" /></div');
padre.appendTo(v);
$('.pwd').focus();

It might help to add then recall the code to get focus.

Upvotes: 3

nickf
nickf

Reputation: 546035

passInput is the <div> element, not the <input>, which is why it can't get focus.

Change it to this:

passInput.find("input").focus();

You could actually rewrite that whole function into one chained statement like so:

$(this)
    .parent()
    .append($(document.createElement("div"))
        .append($('<input type="password">').focus())
    )
    .end()
    .remove();

Though, off the top of my head, I don't know if it will work to .focus() an element before it gets added to the DOM.

Upvotes: 7

Related Questions