Kaherdin
Kaherdin

Reputation: 2127

append html with a function in it

I have a function onclick that add HTML :

jQuery(".test").click(function() {
    jQuery(this).prevAll("input").val("5")
    jQuery(".after").append("<div><input /><a class='.test'>click doesn't work !</a></div>")
});

So, when I click on my class .test, the function is triggered. And that works, but I have appended another class .test and when I click on it, the function isn't triggered. Why ? Thanks.

Fiddle : http://jsfiddle.net/csL8G/3/

Upvotes: 0

Views: 87

Answers (3)

jtheman
jtheman

Reputation: 7491

Use this to check for dynamically added .test elements:

jQuery("body").on('click', '.test', function() {
   jQuery(this).prevAll("input").val("5");
   jQuery(".after").append("<div><input /><a class='.test'>click doesn't work !</a></div>");
});

If you are using jQuery less than 1.8 then use live instead:

jQuery('.test').live('click', function() { ...

Basically the reason is because when the DOM loads then the initial click function just applies to elements already IN the document. But with the on() handler you sets a listener to check within the realm (body) which content has the test class and makes the click event work on that...

Upvotes: 1

Heart
Heart

Reputation: 518

Hey Check your html you have written:

<a class=".test"></a>

it should be only class="test"

jQuery("body").on('click', '.test', function() {
   jQuery(this).prevAll("input").val("5");
   jQuery(".after").append("<div><input /><a class='test'>click doesn't work !</a></div>");
});

Upvotes: 0

Talha Ahmed Khan
Talha Ahmed Khan

Reputation: 15433

you can use jQuery.on() method if you are using jQuery 1.7+

//.on( events [, selector] [, data], handler(eventObject) )

$(document).on('click', '.test', function(){
   //....
});

for previous versions u can use .live() or .bind() methods.

Upvotes: 2

Related Questions