Is there a jQuery plugin to sort a list?

Is there a jQuery plugin that will allow you to sort the list of elements ( <li>...</li>) according to their metadata stored as a hidden element? For example, each list item has two hidden inputs: authorand year. I want to sort the list using these hidden elements. I wonder if there is a ready-to-use plugin for jQuery. So far I have not found such a plugin. The only thing I found was sorting tables.

<ul>
  <li>Position 1
    <input type="hidden" name="author" value="Peter"/>
    <input type="hidden" name="year" value="2004"/>
  </li>
  <li>Position 2
    <input type="hidden" name="author" value="John"/>
    <input type="hidden" name="year" value="2005"/>
  </li>
  <li>Position 3
    <input type="hidden" name="author" value="Tony"/>
    <input type="hidden" name="year" value="2006"/>
  </li>
</ul>
+3
source share
1 answer

Here you go:

<ul>
  <li>Position 1
    <input type="hidden" name="author" value="Peter"/>
    <input type="hidden" name="year" value="2004"/>
  </li>
  <li>Position 2
    <input type="hidden" name="author" value="John"/>
    <input type="hidden" name="year" value="2005"/>
  </li>
  <li>Position 3
    <input type="hidden" name="author" value="Tony"/>
    <input type="hidden" name="year" value="2006"/>
  </li>
</ul>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>

<script type="text/javascript">
    jQuery.fn.sort = function() {  
        return this.pushStack( [].sort.apply( this, arguments ), []);  
    };  

    function mySorter(a,b){  
         return $(a).find("[name=author]").val() > $(b).find("[name=author]").val() ? 1 : -1;  
    };  

    $(document).ready(function(){
         $('ul li').sort(mySorter).appendTo('ul');
    })

</script>

I adapted it from: http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/

Edit: fixed bug with val () and 'ul'

+1

Source: https://habr.com/ru/post/1720502/


All Articles