Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting in a dropdown

I'm populating a few drop downs from some JSON, it works as expected at the moment but i'm trying to sort the values in the drop downs. For all my drop downs it works fine, except for one of them which has numbers in, in which case it lists it 1, 10, 12, 2.

Any ideas how i can keep it sorting alphabetically for everything else but get the sort to work with the numeric values too?

Here's my JS (this replicates for each field - probably should try to find a way to make this reuseable):

var populateGenres = _.map(data.genres, function (val) {
    return '<option>' + val + '</option>';
}).join();
 var target = '#genreField';
$('#genreField').html(populateGenres);
reArrangeSelect(target);

Here's the sort JS:

function reArrangeSelect(target) {
    $(target).html($(target + " option").sort(function(a, b) {
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
    }))
}

My HTML is in this format:

<td>
    <select id="genreField" class="form-control"></select>
</td>
<td>
    <select id="authorField" class="form-control"></select>
</td>
like image 813
Hagbard Avatar asked Dec 19 '25 23:12

Hagbard


2 Answers

function reArrangeSelect(target) {
  $(target).html($(target + " option").sort(function(a, b) {
    // u can use that 'getValue' function
    // for "a.text == 'some string'" it will return 'some string' (string type), 
    // for "a.text == '10'" it will return 10 (number type)
    var aVal = getValue(a.text);
    var bVal = getValue(b.text);
    return aVal == bVal ? 0 : aVal < bVal ? -1 : 1;
  }));
}

function getValue(val) {
 var asNumber = parseFloat(val);
 return isNaN(asNumber) ? val : asNumber;
}
like image 172
Eru Iluvatar Avatar answered Dec 22 '25 14:12

Eru Iluvatar


You can sort data.genres before running it through the _.map functions:

data.genres.sort(function (a, b) {
    a = parseInt(a, 10);
    b = parseInt(b, 10);
    if(a > b) {
        return 1;
    } else if(a < b) {
        return -1;
    } else {
        return 0;
    }
});

Once you sort the data then run your _.map snippet:

var populateGenres = _.map(data.genres, function (val) {
    return '<option>' + val + '</option>';
}).join();

All of your options should now be sorted before you append them to the <select>.

DEMO

like image 35
War10ck Avatar answered Dec 22 '25 13:12

War10ck