Is there a jQuery plugin that will allow to sort a list of items (<li>...</li>) according to their meta data stored as a hidden element? For instance every list item has two hidden inputs: author and year. I want sort the list using those hidden elements. I wonder if there is a ready to use plugin for jQuery. So far, I have not found such plugin. The only I have found are for table sorting.
<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>
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 error with val() and 'ul'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With