3

I have a list which makes use of Jquery UI Sortable. Each list item has a special data-itemid value which is a unique number. User can add items to this list and then sort them. I want to find the max value of the data-itemid attribute regardless of their position in the list.

Before I had implemented Sortable, I could just fetch the value of last-child using $('li:last-child').data('itemid') but after integrating the sorting functionality, the last child might not have the maximum value.

My code is as follows:

HTML

<ul id='sortable'>
   <li data-itemid='1'>One</li>
   <li data-itemid='2'>Two</li>
</ul>

Javascript

$(document).ready(function(){
  maxItemId = $('li:last-child').data('itemid');
  alert('Max Item Id is: ' + maxItemId);
});

I figured I could just go through each li item and look for the one with the max Id, I was hoping there was a better alternative to it.

Akshay Khetrapal
  • 2,586
  • 5
  • 22
  • 38

2 Answers2

3

Something like this should do the work:

var max = 0;
$('#sortable li').each(function(){
    var val = $(this).data('itemid');
    if(val > max) max = val;
});
alert(max);

Another idea is to check after modification, if the last element is the bigger and your user add a new element in the and of the list you can just check those two:

var max = $('li:last-child').prev().data('itemid');
var lastValue = $('li:last-child').data('itemid');
if(lastValue > max) max = lastValue;
alert(max);

But if you don't have a huge number of <li> to check I suggest the first one that is safer and easier.

Hope this helps

wezzy
  • 5,897
  • 3
  • 31
  • 42
  • Well, I guess looping through all the items is the only way. I'll wait some more to see if anything else turns up otherwise I'll accept your answer. This seems like the best way to go. – Akshay Khetrapal Jun 16 '15 at 21:07
  • I don't think that there are a different way about sortable, maybe a slightly faster solution is to do just one comparation, the current max with the new element to check if the new element is bigger otherwise max is the last element. In this way you have less comparations – wezzy Jun 16 '15 at 21:09
  • Well, the value of the new element is basically `currentmax + 1` So, I guess this is the best way to do it. I'll take it. – Akshay Khetrapal Jun 16 '15 at 21:11
  • I've edited the asnwer – wezzy Jun 16 '15 at 21:12
  • 1
    Nah, the second one won't probably work considering the element with the bigger id could be way back in the line. I'll go with the first one. – Akshay Khetrapal Jun 16 '15 at 21:15
2

This puts the data attributes in an array, which is passed to Math.max.apply:

var max= Math.max.apply([], $('li[data-itemid]').map(function() {
  return $(this).data('itemid');
}).get());

Fiddle

Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79