jake
jake

Reputation: 1939

jQuery Issue: functions won't work on newly created HTML element

I have two functions: one that creates a new <textarea> when a button is clicked, and a second function that performs an action when the <textarea> is clicked (or blurred, changed, etc.) That second function selects elements based on a class name. It seems that the second function only works on those matching elements that existed when the page was loaded, but it will not activate on any newly created <textarea> elements. Can anyone figure out why and how to fix this? You'll find the code below. Thanks. --Jake

$('#add').click(function() {
    $(this).before("<textarea class='test'></textarea>")
})

$('.test').blur(function () {
    alert('just a test')
})

Upvotes: 0

Views: 367

Answers (2)

user113716
user113716

Reputation: 322492

You can bind it directly:

$('#add').click(function() {
    $(this).before("<textarea class='test'></textarea>").prev().blur(function () {
        alert('just a test');
    });
});

Or place use jQuery's .delegate() method to place a handler on the parent of #add.

$('#add').click(function() {
    $(this).before("<textarea class='test'></textarea>")
}).parent().delegate('.test','blur',function() {
    alert('just a test');
});

This is a more efficient approach than using .live().

Upvotes: 1

Surreal Dreams
Surreal Dreams

Reputation: 26380

The textarea you create isn't around at the time jQuery assigns the action to elements tagged with the .test class. You'll need the live() function to make this work as desired.

$('.test').live('blur', function () {
    alert('just a test')
});

Now any element tagged with .test will automatically bind the specified function on blur no matter when it's created.

Upvotes: 5

Related Questions