views:

262

answers:

5

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"

A: 

Remove the first item from the select box and then append it at the first position after the sort function.

$(selectId).html($(selectId + " option:not(':first-child')").sort(function(a, b) {
       return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
    }))
rahul
+1  A: 

Theoretically, I would approach the problem by removing the "Please select" entry, sorting the list, then append it again, once the sorting is done

Daniel
A: 

How about always returning -1 for that item?

$(selectId).html($(selectId + " option").sort(function(a, b) {
   return a.text == "Please select an item from the list" ? -1 : a.text < b.text ? -1 : 1;
});

more dynamically:

$(selectId).html($(selectId + " option").sort(function(a, b) {
   return a.text == $(selectId + 'option:first').text ? -1 : a.text < b.text ? -1 : 1;
});
David Hedlund
A: 

If the "Please select..." option has a certain value (here called "dummyVal") associated with it, you could use this in your comparison function:

function sortDropDownListByText(selectId, dummyVal) {
    $(selectId).html($(selectId + " option").sort(function(a, b) {
        if (a.value == dummyVal) {
            return -1;
        }
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
    })) 
}
Tom Bartel
+5  A: 
function sortDropDownListByText(selectId) {
    foption = $('#'+ selectId + ' option:first');
    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.

simplyharsh