0
// 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?

5
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… is this what you are looking for? Commented Nov 30, 2020 at 15:12
  • 1
    In the each loop, If you use prepend instead of append, the list will be reversed. Commented Nov 30, 2020 at 15:15
  • @LouysPatriceBessette this worked! thank you so much! Commented Nov 30, 2020 at 15:20
  • @Kajbo the console says the reverse function doesn't exist when I tried adding it after .text(base) Commented Nov 30, 2020 at 15:20
  • Using .reverse() would work too, but you have to apply it on the array before looping with each. Commented Nov 30, 2020 at 15:28

2 Answers 2

2

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 ;)

Sign up to request clarification or add additional context in comments.

Comments

0

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

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.