0

I am trying to use jQuery to delete rows in a table. The table presents a button as the first item in a row. clicking on that button should delete that row from a MySQL table.

Here is the javascript code

      $("#list .del").click(function() {
      cell = $(this);
      row  = cell.closest("tr");
      vid = row.find (".vid");
      alert (vid.text());

      $.post ("db_deleteplayer.php",
        {vid:vid.text()},
        updateSignup);
      return;

    }) //#list .del click      


    function updateSignup(data) {
        $('#list').html(data);
      return;
    }

This works perfectly for the first row I want to delete but fails thereafter. I've confirmed this in Firefox, Chrome, and IE.

My guess is that the first deletion is modifying the DOM and jQuery gets confused. Could someone please explain where I'm going wrong?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
delpi767
  • 37
  • 6

2 Answers2

7

Change:

$("#list .del").click(function({

to:

$("#list").on('click', '.del', function(){

Basically, when you call $('#list').html(..) you are replacing the elements within #list, and in doing so, you remove the previously bound event handlers.

By replacing with .on('click', '.del', function..., you're attaching the handler to the #list, which always remains in the DOM (in your example). The handler then checks for the events original target, to see if it has the class .del, and executes the handler if it does.

Read more about delegated events: https://stackoverflow.com/a/8111171/1238887

Community
  • 1
  • 1
ahren
  • 16,803
  • 5
  • 50
  • 70
  • Thanks, this works like a champ. Those of you who take time to answer questions are not only appreciated but you save the rest of us hours (I'd already spent 2 on this) of time. – delpi767 Nov 19 '12 at 23:26
0

What about this? This will simply remove the row that the button .del was in (so it won't actually update it). Of course it depends on your setup whether or not you can find this useful, but if .del is inside of the row, it should work fine.

$("#list .del").click(function(e) {
    var row = $(this).closest("tr");
    $.post(
        "db_deleteplayer.php",
        {
            vid: row.find(".vid").text()
        },
        function(data) {
            row.remove();
        }
    );

    e.stopPropagation();
    e.preventDefault();
});
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
  • Thank you. This works fine also. I guess what I'd need to do to confirm the deletion is have db_deleteplayer.php return a code confirming the delete. – delpi767 Nov 19 '12 at 23:30