2

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

4 Answers 4

8

You're using .click(function () { }) which matches the elements currently in the DOM and binds onclick handlers to them. When you remove those elements, or replace them with new ones, the onclick handlers are lost. The code which selects .delete has 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:

$('.delete').live('click', function(e) {
  // ...
});

This listens for click events to bubble up and checks if their triggering element matches the selector used to bind the .live callback. 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.

2
  • thanks heaps !! totally worked ... also this script totally doesnt work in safari .. jquery thing is not working in my safari at all ..any clue ??
    – abnab
    Sep 1, 2011 at 15:06
  • @Abhinab that isn't a useful description of the problem. Please ask another question and provide more details, the comments aren't for additional questions/answers.
    – user229044
    Sep 1, 2011 at 15:11
6

I think you should use live()

$('.delete').live('click', function(

so that the event handler is attached also to newly created elements. This is because the click() handler applies only to elements already present when the dom is loaded, while live() also 'works' with elements added afterwards. This is how it's done (taken from the documentation)

Event Delegation The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to .live() is never bound to an element; instead, .live() binds a special handler to the root of the DOM tree. In the example above, when the new element is clicked, the following steps occur:

  • A click event is generated and passed to the for handling.
  • No handler is directly bound to the , so the event bubbles up the DOM tree.
  • The event bubbles up until it reaches the root of the tree, which is where .live() binds its special handlers by default.
  • The special click handler bound by .live() executes.
  • This handler tests the target of the event object to see whether it should continue. This test is performed by checking if $(event.target).closest(".clickme") is able to locate a matching element.
  • If a matching element is found, the original handler is called on it.

Because the test in step 5 is not performed until the event occurs, elements can be added at any time and still respond to events.

3
  • You should add some info as to WHY he should use live() and why the click() function doesn't work with newly created elements. Otherwise, its the right answer. Just not too helpful atm. Sep 1, 2011 at 15:05
  • Nothing will be "attached" to newly created elements, that isn't how live works
    – user229044
    Sep 1, 2011 at 15:06
  • I know, i was speaking "metaforically", just to exaplain things, i'll add the proper explanetion from the documentation Sep 1, 2011 at 15:08
0

you need to use Jquery live() function http://api.jquery.com/live/

$('.delete').live('click', function( ){

     });
0

Assuming that the edit/delete elements are inside of #tabledata, when you replace the content, those original edit/delete elements that the functions were attached to no longer exist. I'd look at using jQuery.live, since it will work even when new elements with .edit or .delete are added.

$('.delete').live('click', function(e) {
    var bid = this.class; 
    ...
    ...
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.