Sort Select by ID javascript

3

Personal I have a select via ajax that pulls the data from my bank but at the time of submitting the select, I'm not able to display by order of ID Grow ,

<div class="modal-body">
                <div id="lista-hospitais-loader" class="loader-120 center-block"></div>
                <div id="lista-hospitais-content" class="form-group">
                    <label>Selecione o Centro:</label><br />
                    <select id="hospital-change-list" data-live-search="true" data-width="75%"></select>
                </div>
            </div>
$.ajax({
            method: 'POST',
            url: '/Gerencial/Centro/GetHospitais',
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    var option = '<option value="' + data[i].CentroId + '">' + data[i].CentroId + ' - ' + data[i].Nome + '</option>';
                    $('#hospital-change-list').append(option);
                }

                $('#lista-hospitais-loader').fadeOut(1300, function () {
                    $('#hospital-change-list').selectpicker();
                    $('#lista-hospitais-content').fadeIn(100);
                    $('#change-ok').removeAttr('disabled');
                });
            }
        });

    
asked by anonymous 10.05.2017 / 15:53

2 answers

5

You can sort your drop using the sort(); method, it allows you to sort the elements through any attribute, for more information about the method at documentation ,

* In your case it would be:

var drop = $('#hospital-change-list option');

drop.sort(function(a,b){
    a = a.value;
    b = b.value;

    return a-b;
});

$('#hospital-change-list').html(drop);

Here is a working example of how the method works:

var drop = $('#drop option');

drop.sort(function(a,b){
    a = a.id;
    b = b.id;
 
    return a-b;
});

$('select').html(drop);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="drop">
  <option id="1">Um</option>
  <option id="3">Tres</option>
  <option id="4">Quatro</option>
  <option id="2">Dois</option>
  <option id="7">Sete</option>
  <option id="5">Cinco</option>
  <option id="6">Seis</option>
</select>
    
10.05.2017 / 16:01
1

    
10.05.2017 / 16:27