gordon613
gordon613

Reputation: 2952

Adding options to a select using jQuery - changing the order

I wrote the following code to populate a listbox in Jquery (based on What is the best way to add options to a select from an array with jQuery?)

function populate(id, selectValues, theSelected, empty) {
    if (empty) {
        $(id).empty();
    }
    $.each(selectValues, function(key, value) {
        $(id).append($("<option></option>").attr("value", key)
             .prop('selected', key == theSelected).text(value));
    });
}

I call the function using e.g. the following code

populate('#BASE1', {
    "8": "2012 average=100",
    "7": "2010 average=100",
    "6": "2008 average=100",
    "5": "2006 average=100",
    "4": "2002 average=100",
    "3": "2000 average=100",
    "2": "1998 average=100",
    "1": "1993 average=100"
}, selectedBase, true);

However the list is ordered in the order of the ID - i.e. List in reverse order

How can I adapt my populate function to order them in the order in which I list them? (Obviously I could re-assign the ID's but I was wondering if there is another solution)

Upvotes: 1

Views: 63

Answers (2)

dfsq
dfsq

Reputation: 193261

The issue it that you can't rely on order of object properties, there is simply no such thing as order for them. Instead use an array of objects.

Improved code will look like this:

function populate(id, selectValues, theSelected, empty) {
    if (empty) {
        $(id).empty();
    }
    $.each(selectValues, function(i, obj) {
        $(id).append($("<option></option>").attr("value", obj.id)
             .prop('selected', obj.id == theSelected).text(obj.text));
    });
}

var selectedBase = 3;

populate('#BASE1', [
    {id: "8", text: "2012 average=100"},
    {id: "7", text: "2010 average=100"},
    {id: "6", text: "2008 average=100"},
    {id: "5", text: "2006 average=100"},
    {id: "4", text: "2002 average=100"},
    {id: "3", text: "2000 average=100"},
    {id: "2", text: "1998 average=100"},
    {id: "1", text: "1993 average=100"}
], selectedBase, true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="BASE1"></select>

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82231

change .append() to .prepend():

$.each(selectValues, function(key, value) {
    $(id).prepend($("<option></option>").attr("value", key)
         .prop('selected', key == theSelected).text(value));
});

Working Demo

Upvotes: 2

Related Questions