delete

JQuery click function not working after ajax call?

JQuery click function works fine here

<div id="LangTable"><a class="deletelanguage">delete</a></div> $('.deletelanguage').click(function(){ alert("success"); }); 

but if i set some <a> ajax, $('.deletelanguage').click does not work.

eg

 function CreateRow(jdata) { $('#LangTable').append('<a class="deletelanguage">delete</a>'); } $.ajax({ url: "/jobseeker/profile/", success: CreateRow }); 

Now $('.deletelanguage').click for the last <a> does not work.

Jsfiddle example: http://jsfiddle.net/suhailvs/wjqjq/

Note: CSS works fine here.

I want these newly added <a> work with jQuery click.

+47
jquery dom html ajax
Jul 18 '13 at 5:35
source share
7 answers

The problem is that .click only works for elements already on the page. You should use something like on if you are connecting future elements

 $("#LangTable").on("click",".deletelanguage", function(){ alert("success"); }); 
+125
Jul 18 '13 at 5:40
source share

When you use $('.deletelanguage').click() to register an event handler, it adds the handler only to those elements that exist in dom when the code is executed

you need to use delegation based event handlers.

 $(document).on('click', '.deletelanguage', function(){ alert("success"); }); 
+45
Jul 18 '13 at 5:38 on
source share
 $('body').delegate('.deletelanguage','click',function(){ alert("success"); }); 

or

 $('body').on('click','.deletelanguage',function(){ alert("success"); }); 
+14
Jul 18 '13 at 5:37 on
source share

Since the class is added dynamically, you need to use event delegation to register an event handler, for example:

 $('#LangTable').on('click', '.deletelanguage', function(event) { event.preventDefault(); alert("success"); }); 

This will add your event to any anchors in the #LangTable element, reducing the scope of checking the entire tree of document elements and increasing efficiency.

FIDDLE DEMO

+6
Jul 18 '13 at 5:39 on
source share

Here is fiddle

Same code as yours, but it will work with dynamically generated elements.

 $(document).on('click', '.deletelanguage', function () { alert("success"); $('#LangTable').append(' <br>------------<br> <a class="deletelanguage">Now my class is deletelanguage. click me to test it is not working.</a>'); }); 
+2
Jul 18 '13 at 5:39 on
source share

A click event does not exist where the event is defined. You can use live or delegate an event.

 $('.deletelanguage').live('click',function(){ alert("success"); $('#LangTable').append(' <br>------------<br> <a class="deletelanguage">Now my class is deletelanguage. click me to test it is not working.</a>'); }); 
+2
Jul 18 '13 at 5:39 on
source share

I tested a simple solution that works for me! My javascript was in a separate js file. I did what I put javascript for the new element in the html that ajax loaded, and it works great for me! This is for those who have large javascript files!

+1
Jul 13 '14 at 9:24
source share



All Articles