Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort items in a dropdown list without the first item

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"

like image 627
leora Avatar asked Jan 12 '10 12:01

leora


People also ask

How do I select the first element in a dropdown?

So you could use $("select"). prop("selectedIndex",0); for a quick way to select the first option on all dropdowns.

How do you sort options in Javascript?

sort() The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

How do I get all the values in a drop down?

We can extract all the options in a dropdown in Selenium with the help of Select class which has the getOptions() method. This retrieves all the options on a Select tag and returns a list of web elements. This method does not accept any arguments.


2 Answers

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.

like image 166
simplyharsh Avatar answered Oct 17 '22 17:10

simplyharsh


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

like image 27
Daniel Avatar answered Oct 17 '22 16:10

Daniel