Ashwin
Ashwin

Reputation: 12431

Attach focus event on dynamic textarea

I want to attach a focus event on dynamically created textarea element. I have created a fiddle below which describes my problem. When I click on 'click' link another text area is created. It doesn't get focus event.

$("textarea").on("focus", function(){
    alert("textarea focus");
    $(this).blur();
});

$("a").click(function(){
    $("div").append("<textarea>2</textarea>");
});

http://jsfiddle.net/LepvD/2/

How can I add focus event on dynamic textarea? I want to avoid again attaching focus again and again for each new element

Upvotes: 0

Views: 7227

Answers (3)

Satpal
Satpal

Reputation: 133453

Use Delegated events, as they have the advantage that they can process events from descendant elements that are added to the document at a later time.

As you are creating textarea dynamically.

You need to use Event Delegation. You have to use .on() using delegated-events approach.

$("div").on("focus", "textarea", function(){
    alert("textarea focus");
    $(this).blur();
});

Live Demo

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82251

you shouild use event delegation.use:

 $(document).on("focus","textarea", function(){
    alert("textarea focus");
    $(this).blur();
});

Working Fiddle

Upvotes: 1

Felix
Felix

Reputation: 38112

You need to use event delegation here since your textarea is dynamically created:

$(document).on("focus","textarea", function(){
    alert("textarea focus");
    $(this).blur();
});

It will helps you to bind the focus event on these newly added textarea

Updated Fiddle

Upvotes: 3

Related Questions