OBAID OBAID - 1 year ago 200
Javascript Question

check last iteration in .each jQuery

Sorry for my bad English.
How can we check last iteration of jQuery.each() loop. i want to check iteration of loop is last or not. My loop is iterating on an object coming from ajax success.

here is my code

url: "<?php echo $this->getUrl('xs4arabia/index/getFetchrOrderLogs/'); ?>",
type: "GET",
data: {tracking_id: tracking_id},
dataType: "json",
success: function (data) {
jQuery.each(data, function (key, value) {

Answer Source

The first parameter passed to the each() handler function is the index of the current element in the array (although you've currently named it key). You can compare that to the length of the array to find out your current position:

$.each(data, function(index, value) {
    var isLastElement = index == data.length -1;

    if (isLastElement) {
        console.log('last item')

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download