Here goes my question..

/* I am using ajax to dynamically create table */
$(".n").click(function(){
var id= $(this).closest('tr').find('td.ide2').html();
//for displaying the table
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>Admin/show', //We are going to make the request to the method "list_dropdown" in the match controller
dataType:'json',
data: {'id':id}, //POST parameter to be sent with the tournament id
success: function(resp) {
for(var i=0;i<(resp.length);i++)
{
var row = $('<tr></tr>').appendTo($("#unique-list"));
$('<td />',{text:resp[i]}).appendTo(row);
$('<td class="off-del glyphicon glyphicon-minus"></td>').appendTo(row);
}//end for loop
} //end success
}); //end ajax
$(".off-del").click(function(){
alert('hello');
var id= $(this).closest('tr').find($(":first-child")).html();
console.log(id);
});
});
the event click on $(".off-del") is not triggering automatically I have to write in console the name of the event then this event starts functioning. Is there any issue with class name generating dynamically and how to overcome
After i wrote the name of the event in console it works 
Ajax calls are asynchronous.
Before the elements are appended via ajax, the click handler gets registered, which find no elements with $(".off-del").
You should probably use event delegation.
$(document).on('click','.off-del',function(){
alert('hello');
var id= $(this).closest('tr').find($(":first-child")).html();
console.log(id);
});
Instead of $(document) you can use a static parent.
When you set up an event handler in jQuery like this:
$(".off-del").click(function(){
alert('hello');
var id= $(this).closest('tr').find($(":first-child")).html();
console.log(id);
});
you're telling it to go find the elements with class "off-del" in the document right at that moment. Your ajax operations will add such elements, but it'll only happen after your attempt to set up the handlers.
Instead of that, you can set up the handler on the document object and take advantage of event bubbling:
$(document).on("click", ".off-del", function() {
alert('hello');
var id= $(this).closest('tr').find($(":first-child")).html();
console.log(id);
});
You can set up the event handler that way any time you want, and it'll handle clicks from any ".off-del" element added at any time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With