Search code examples
jqueryselectparent

jQuery: Having trouble selecting/acting on parent element


I'm playing around with jQuery and AJAX for the first time, and I seem to have run into a little stumbling block in trying to delete an entry from the database. Or, to be clearer, the item gets deleted from the database successfully, but I can't seem to select the correct element to hide once it's deleted.

Here's what some sample code looks like (in this case, I'm simply trying to change the background color for testing purposes: I'll be using fadeOut or equivalent in my production environment -- more explanation follows):

    //When link with class .deleter is clicked, get the parent element's id (which is also that element's id in the database)
    $('.deleter').click(function() {
        var recordToDelete = $(this).closest('ul').attr('id');

    //Send the id to the PHP script, which returns 1 if successful and 0 if not
        $.post("databasefuncs.php?func=delete", { postedMessage : recordToDelete },
            function(result){
                if(result == 1) {
                    //Change the background color of the parent UL to red if successful
                    $(this).closest('ul').css('background-color', 'red');
                } else {
                    //Change the background color of the parent UL to blue if successful
                    $(this).closest('ul').css('background-color', 'blue');
                }

            });
    });

To clarify what it looks like on the front-end, my ULs are set to display: table-row, my LIs are set to display: table-cell, and I have a DIV that contains them all and is set to display: table. Essentially, I have a UL per record and an LI per column in each record.

Thanks!


Solution

  • You have different context inside AJAX callback. So, $(this) points to another object. I suggest you should use closure - variable "item" in following example:

    //When link with class .deleter is clicked, get the parent element's id (which is also that element's id in the database)
    $('.deleter').click(function() {
        var item = $(this).closest('ul');
        var recordToDelete = item.attr('id');
    
    //Send the id to the PHP script, which returns 1 if successful and 0 if not
        $.post("databasefuncs.php?func=delete", { postedMessage : recordToDelete },
            function(result){
                if(result == 1) {
                    //Change the background color of the parent UL to red if successful
                    item.css('background-color', 'red');
                } else {
                    //Change the background color of the parent UL to blue if successful
                    item.css('background-color', 'blue');
                }
    
            });
    });