sort items in a dropdown list without the first item
21,984
Solution 1
function sortDropDownListByText(selectId) {
var foption = $('#'+ selectId + ' option:first');
var soptions = $('#'+ selectId + ' option:not(:first)').sort(function(a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
});
$('#' + selectId).html(soptions).prepend(foption);
};
is your function.
Solution 2
Theoretically, I would approach the problem by removing the "Please select" entry, sorting the list, then append it again, once the sorting is done
Author by
leora
Updated on August 19, 2020Comments
-
leora over 3 years
I have the following code to sort the items in a dropdown list:
function sortDropDownListByText(selectId) { $(selectId).html($(selectId + " option").sort(function(a, b) { return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 })) }
this works fine except in cases where, in my first item, i have a **"Please select and item from the list" message . . **
is there anyway i can sort the items in the select list and keep the "Please select entry" as the first item in the list always?
EDIT:
In response to some of the answers, the "Please select item always has a value of 0"