Sorting all selected dropdowns
I have been trying to get a more dynamic solution than naming all dropdowns individually and I believe I have missed the selector boat. I want to do something like the following:
$(function () {
// loop through all the lists
$("select").each(function(){
var myId = $(this).attr('id');
sortDropDownListByText(myId);
});
// pass the Id to a function to sort
function sortDropDownListByText(selectId) {
$(selectId).html($(selectId + " option").sort(function(a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
}
});
My end goal will have a CSS class as the selector rather than all but I feel that t开发者_运维百科he solution here will give me what I need there.
If you are open to a little sort plugin, this one is decent tinysort and has flexible usage like:
// sort by the element's text
$("ul#people>li").tsort();
// sort by a child's text
$("ul#people>li").tsort("span.surname");
// sort by the img element, order descending using the img's "alt" attribute
$("ul#people>li").tsort("img",{order:"desc",attr:"alt"});
Also there is a blog post that goes over this as well http://blog.pengoworks.com/index.cfm/2008/9/11/Sorting-DOM-elements-using-jQuery
The following solved my initial question. :)
$(document).ready(function () {
$('select').each(function () {
sortDropDownListByText(this);
});
});
// pass the select object to a function to sort
function sortDropDownListByText(selectObject) {
$(selectObject).html($("option", selectObject).sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
}));
}
精彩评论