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);
}
});
You could try checking the children count of the element:
if ($('#item-list').children().length <= 0) {
// Show your message
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.