-1

i am trying to target 'clicked' element on successful Ajax return, when multiple elements have same class name.

  <td data-name='tom' class="status"><a href="">click</a></td>
  <td data-name='jack' class="status"><a href="">click</a></td>
  <td data-name='phil' class="status"><a href="">click</a></td>

I am able to target the clicked element using this.i.e:

  var name  =  $(this).attr("data-name");

I am however unclear how to target that same element on successful ajax return.

below is my ajax code example:

   $(".status").click(function(event){
            event.preventDefault();
            var name  =  $(this).attr("data-name");

            $.ajax({
                url: FORM_URL,
                type: "POST",
                data: {name:name},
                showLoader: true,
                cache: false,
                success: function(data){

                    var el = $(this)('.status');
                    el.empty();

                        el.append(
                            '<div class="status">' +
                            '<p>name changed</p>' +
                            '</div>'
                        )
                    }
                },
              
            });
            return false;
        });

The 'this' does not work on ajax success

theSeeker
  • 297
  • 4
  • 12
  • Does this answer your question? [jQuery how to find an element based on a data-attribute value?](https://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a-data-attribute-value) – freedomn-m Oct 07 '21 at 09:05
  • While the answer to keep `this` in a variable is viable, you could also use the attribute selector on name `var el = $("[data-name='" + name + "']")` – freedomn-m Oct 07 '21 at 09:06
  • @mayankpatel why did you delete your viable answer? Just need to change `var el = $(self)('.status')` to `var el = self` – freedomn-m Oct 07 '21 at 09:23

1 Answers1

0

keep element as a variable like so -

statusElement = document.querySelector('.status');

then add event listener and use the variable inside your function -

statusElement.addEventListener('click', function(event) {
    statusElement.empty();    
})
Guy Perry
  • 306
  • 1
  • 7