Sort Select by javascript ID

Asked

Viewed 376 times

3

Folks I have a select via ajax pulling data from my database only when it comes to presenting the select, I’m not being able to present in order to ID Crescent,

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

inserir a descrição da imagem aqui

2 answers

5


You can sort your drop using the method sort();, it enables the sorting of the elements through any attribute, for more information on the method a look at documentation,

*In your case I’d 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);

follows a functional 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>
<select id="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>

  • friend I managed to settle here, but thank you still for your help!

  • 1

    Wonder, but it is registered as "Sort Select by javascript ID":D

1

People I managed to solve, when I do select in the bank, my order by was pulling by name, in that I changed by the center ID!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.