Find the maximum value of a data attribute for all li elements

I have a list that uses JQuery UI Sortable. Each item in the list has a special data-itemid value, which is a unique number. The user can add items to this list and then sort them. I want to find the maximum value of the data-itemid attribute regardless of their position in the list.

Before I implemented Sortable, I could just get the last-child value with $('li:last-child').data('itemid')

, but after integrating the sort function, the last child may not have a maximum value.

My code looks like this:

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 element and look for the one with the maximum Id, I was hoping there was a better alternative to it.

+3


source to share


2 answers


Something like this should do the job:

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 item is larger and your user adds a new item to and from the list, you can just check these 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 large number <li>

to check, I suggest the first one, which is safer and easier.

Hope it helps

+3


source


This puts the data attributes into 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

+2


source







All Articles