SecureEntrepeneur
SecureEntrepeneur

Reputation: 97

Reversing Order of Select List in Javascript & HTML

// Generate and append Base array from DB based on ID selected
function BasePopulation(id) {

    // Use previous query
    var array = dropdownRequest.responseJSON[id];
    
    // Create Base dropdown
    $("#inputGroup")
        .append(
            '<div class="col-12 col-sm-12 col-md-8 col-lg-8 col-xl-8 removable">' +
                '<select id="BaseSelect" name="BaseSelect" class="selectpicker" data-size="10" data-width="auto" data-container="body" title="Base">' +
                    '<option>Base</option>' +
                    '<!-- Populated in .js -->' +
                '</select>' +
            '</div>'
        );

    // Populate Base dropdown
    
    $.each(array, function(index, base) {
        // Reformat JD Base
        var base_value = BaseToValue(base);
    
        $("#BaseSelect")
            .append($("<option class='removable'></option>")
            .attr("value", base_value)
            .text(base));
    });
    
    $("#BaseSelect").selectpicker("refresh");
    
}

I'm trying to reverse the order of the dropdown list in HTML/Javascript, but I can't find a reverse function. Is there a function to do this, or do I have to do this manually?

Upvotes: 0

Views: 587

Answers (2)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

There are two possible ways for you to populate the dropdown reversly.

1: with jQuery .prepend() method instead of .append()

$.each(array, function(index, base) {
    // Reformat JD Base
    var base_value = BaseToValue(base);

    $("#BaseSelect")
        .prepend($("<option class='removable'></option>")  // Using prepend
        .attr("value", base_value)
        .text(base));
});

2: with the JS .reverse() method applied on the array

array.reverse()

$.each(array, function(index, base) {
  ...

Read the documentation for more details ;)

Upvotes: 2

vazsonyidl
vazsonyidl

Reputation: 471

If you reverse this var array = dropdownRequest.responseJSON[id]; array with the .reverse function?

Upvotes: 0

Related Questions