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.
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"); }); 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"); }); $('body').delegate('.deletelanguage','click',function(){ alert("success"); }); or
$('body').on('click','.deletelanguage',function(){ alert("success"); }); 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.
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>'); }); 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>'); }); 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!