TlonXP
TlonXP

Reputation: 3485

Add values to a Select and sort

I have several Select which depend on each other if I select a value in one of the other is removed, and the previous value is added to others, how I can add the previous value by JQuery to Select? and then sort it alphabetically?

Upvotes: 2

Views: 634

Answers (3)

kprobst
kprobst

Reputation: 16651

Not sure about the sorting (shouldn't be too hard to figure out) but you can append an <option> element to a list like this:

$("#myselect").append(
    $("<option>").prop("selected", "selected").attr("value", "OptionValue").text("OptionText")
);

The first call to prop() is only if you need the element to be the selected one in the list, otherwise you can omit it.

Edit: I went ahead and worked out the sort part:

var elems = [];
$("#sortable > option").each(function () {
    elems.push({ key: $(this).val(), value: $(this).text() });
});

elems.sort(function (a, b) {
    if (a.value < b.value) return -1;
    if (a.value > b.value) return 1;
    return 0;
});

$("#sortable").empty();
$.each(elems, function (idx, item) {
    $("#sortable").append(
        $("<option>").attr("value", item.key).text(item.value)
    );
});

Upvotes: 2

Sahil Kapoor
Sahil Kapoor

Reputation: 614

Since the code for adding values is available, here is the code for sorting values in select

function sortOptions()
{
    var arr = [];
    $("#myselect option").each(function(){
        arr.push($(this).html());
    });
    $('#myselect').empty();
    arr.sort();
    var html='';
    for(var i=0;i<arr.length;i++)
    {
        html+='<option>' + arr[i] + '</option>'
    }
    $('#myselect').html(html);
}

Upvotes: 2

Corsair
Corsair

Reputation: 1044

I guess you can't really "order" the DOM elements.

The best approach for this is propably to read out all the elements of the select to which an element should be added into an array, add the new values to the array and then sort it. The DOM elements should be removed during this process of course. Afterwards you add the newly ordered elements to the DOM again in the desired order.

Upvotes: 1

Related Questions