0

I have a list of items where you can remove them via ajax. Now, when I remove the last item on said list, I'd like it to show a message. I've tried several things, such as asking if the container div has children, but it fails. The code would be something like this:

$.ajax({
        type: "DELETE",
        data: {
            _token : token
        },
        url: "item/" + id,

        success: function (data) {

            $("#item-" + id).fadeOut("normal", function() {
                $(this).remove();
                $("#item-list").not(':parent').text("Nothing to do.");                  
            });

        },
        error: function (data) {
            console.log('Error:', data);
        }
    });
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
C. Todian
  • 25
  • 5
  • Possible duplicate of [Determining if the element is the last child of its parent](http://stackoverflow.com/questions/4209605/determining-if-the-element-is-the-last-child-of-its-parent) – Linek Mar 21 '17 at 20:38
  • Oh, I tried that one, but it didn't work. But thank you! – C. Todian Mar 21 '17 at 20:41

2 Answers2

2

You could try checking the children count of the element:

if ($('#item-list').children().length <= 0) {
     // Show your message
}
Blue Boy
  • 620
  • 1
  • 6
  • 13
  • Hmm... I was thinking of something like this but didn't seem very elegant. But it worked! So that's what counts! – C. Todian Mar 21 '17 at 20:42
0

To Check if last element removed was last element in parent And from the example code provided:

You can try like this:

    $.ajax({
      type: "DELETE",
      data: {
          _token: token
      },
      url: "item/" + id,

      success: function(data) {

          $("#item-" + id).fadeOut("normal", function() {
              $(this).remove();
              if ($(this).attr("id") == $("[id^=item-]:last").attr("id")){
             // here you can check if the removed element's id is
             // same to the last element's id in list
                  alert('last element removed'); }
          });

      },
      error: function(data) {
          console.log('Error:', data);
      }
  });

So this part will return last element in group; while using id and not class you can select elements that starts with the id=item-:

$("[id^=item-]:last")

for further reading go to jQuery API - Selectors & W3 Schools jQuery Selectors

wpcoder
  • 1,016
  • 11
  • 17
  • Please explain ***WHY*** the code should look like that, SO is all about helping people solve a general set of problems, by giving a static example does not help anyone derive significant gain from your answer. Just a heads up – AP. Mar 21 '17 at 21:08