Reputation: 239
I need to check if the current element after using jquery each is the last one in the list i have tried
$('#droplist div.panel').each(function(){
if($(this).last()){
alert($(this).attr('id')+' is the last order');
}else{
alert('Not the last order');
}
});
and
$('#droplist div.panel').each(function(){
if($(this).is(':last')){
alert($(this).attr('id')+' is the last order');
}else{
alert('Not the last order');
}
});
there are a dynamic set of elements, which are being selected, as they are selected I am looping through them and performing calcs as i go along. I need the last one to terminate my calculation functions. ie need to flag that i have reached the last element in the current list.
Thanks all.
Upvotes: 1
Views: 2097
Reputation: 1259
Compare the index and the total number of elements.
JSFiddle: http://jsfiddle.net/9gmdt1fd/
Code:
$( document ).ready(function() {
var objects = $("ul li")
$.each( objects, function( key, value ) {
if(key == objects.length-1){
alert(value+' is the last order');
}else{
alert('Not the last order');
}
});
});
Upvotes: 0
Reputation: 780787
if ($(this).is("#droplist div.panel:last")) {
...
}
or:
var panels = $('#droplist div.panel');
var lastpanel = panels.last();
panels.each(function(){
if($(this).is(lastpanel)){
alert($(this).attr('id')+' is the last order');
}else{
alert('Not the last order');
}
});
Upvotes: 1
Reputation: 4552
You can get the length of the query and compare the current index on the each loop:
var list = $('#droplist div.panel')
var length = list.length;
list.each(function(index){
if(index == length-1){
alert($(this).attr('id')+' is the last order');
}else{
alert('Not the last order');
}
});
Upvotes: 4