edit delete function made through jquery. when I first load the page all works fine. But when I reload the div when data is added or edited. Then the Edit and Delete function doesnt work for the new content.
$('#add').submit(function() {
$.ajax({
type: "POST",
url: "addedit.php",
data: "name="+$('#name').val()+"&address1="+$('#address1').val()+"&address2="+$('#address2').val()+"&suburb="+$('#suburb').val()+"&state="+$('#state').val()+ "&postcode="+$('#postcode').val()+"&customerid="+$('#customerid').val(),
success: function(msg){
//clearing form after adding
$( "form" )[ 0 ].reset();
$('#tabledata').load('load.php');
alert("Sucessfully Added/Edited.")
}
});
//$('#tabledata').html('asd');
return false;
});
//function to chuck customer data into the form to edit
$('.edit').click(function(e) {
var bid = this.class;
var customerid = $(this).closest('tr').attr('id'); // table row ID in which customer id has been stored
$.ajax({
type: "POST",
url: "getedit.php",
data: "id="+customerid,
success: function(msg){
var partsArray = msg.split('||');
//adding form with customer data to edit
$("#name").val(partsArray[0]);
$("#address1").val(partsArray[1]);
$("#address2").val(partsArray[2]);
$("#suburb").val(partsArray[3]);
$("#state").val(partsArray[4]);
$("#postcode").val(partsArray[5]);
$("#customerid").val(customerid);
}
}); //end of $.ajax
}); //end of edit click
//function to delete the customer data
$('.delete').click(function(e) {
var bid = this.class;
var customerid = $(this).closest('tr').attr('id'); // table row ID in which customer id has been stored
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+customerid+"",
success: function(msg){
// $('#'+customerid).css({backgroundColor: 'red'});
$('#'+customerid).remove();
//alert("Sucessfully Deleted.")
// $('#tabledata').load('load.php');
}
});//end of $ajax
}); //end of delete click
You’re using
.click(function () { })which matches the elements currently in the DOM and bindsonclickhandlers to them. When you remove those elements, or replace them with new ones, theonclickhandlers are lost. The code which selects.deletehas already run, and cannot effect newly created elements.To setup a handler which will catch click events for all current and future elements matching
.delete, you need to use.live:This listens for
clickevents to bubble up and checks if their triggering element matches the selector used to bind the.livecallback. This way, even elements which didn’t exist in the DOM when the jQuery code was run will still cause your callback to fire. The process is called event delegation.