7

I have a Listbox with some items on a page. Is there any simple way to sort the items using Jquery or native javascript?

Best Regards,

3 Answers 3

16

You can use a Javascript JQuery function as below. I haven't tested it fully but it must work.

 function Sortit() {
        var $r = $("#MySelect option");
        $r.sort(function(a, b) {
            if (a.text < b.text) return -1;
            if (a.text == b.text) return 0;
            return 1;
        });
        $($r).remove();
        $("#MySelect").append($($r));
        }

Here your select Tag should have an Id MySelect. You can also do this using plain javascript.This will sort by the Displayed Text of the Options. Instead, if you want to sort by the Value of each option, you use a sort as below

 $r.sort(function(a, b) {
               return a.value-b.value;
            });
Sign up to request clarification or add additional context in comments.

Comments

1

I used a method very similar to @josephj1989. However, if your dropdown has strings as values, you still need to assign the 1, -1, or 0 values (at least I did anyway).

function SortList(listname) { 
    var $r = $(listname + " option"); 
    $r.sort(function(a, b) { 
        return (a.value < b.value) ? -1 : (a.value > b.value) ? 1 : 0;
        //or you can have a.text, b.text, etc
    }); 
    $($r).remove(); 
    $(listname).append($($r)); 
} 

Comments

0

If you don't mind using a jQuery plug-in, Tablesorter does a good job.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.