Sort Dropdown with jquery after append [duplicate]

3

If the user does not find the desired item in the dropdown list, it can include a new item, for this I used the prompt function of javascript , and then the user types the name and clicking Ok , if the object is not actually registered in the database (Sometimes for lack of attention, and we do not find the item in the list), the object is registered. After the registration the object is added to the list, however it goes to the end of it.

So I wanted the object to be sorted again after the .append() , leaving it in the position that would be ideal (in alphabetical order).

For this I thought about creating a script that would look in the bank all the items (again) and be inserted again, but I think it is a waste of code. This is the% used%

   $('#NewBrand').click(function () {
        var name;
        name = prompt("Qual a marca?");
        var url = '@Url.Action("CreateBrand", "Ajax")';
        if (name != null) {
            $.ajax({
                type: 'POST',
                url: url,
                data: { name: name },
                dataType: 'json',
                success: function (data) {
                    if (data.Name == name) {
                        alert("A mcarca " + name + " foi cadastrado com sucesso!");
                        $('#Brand').append('<option value="' + data.BrandID + '">' + data.Name + '</option>');
                    } else if (data == false) {
                        alert("Não foi possível cadastrar a marca " + name + "!");
                    } else {
                        alert("A marca " + data.Name + " já está cadastrada");
                    }
                }
            });
        }//if
    });

and here the script of Dropdownlist :

    <div class="form-group">
        @Html.Label("Tipo", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("EquipmentTypelID", null, htmlAttributes: new { @class = "form-control",id="Type", style = "float:left;" })<div class="btn btn-primary" id="NewType" title="Novo Tipo" style="float:left;">+</div>
            @Html.ValidationMessageFor(model => model.EquipmentTypeID, "", new { @class = "text-danger" })
        </div>
    </div>

Is there any way to sort directly by View ?

    
asked by anonymous 19.12.2016 / 21:41

2 answers

4

You can sort the values of options into an array and then sort it. When only .sort() is used without arguments, it already understands ascending and in alphabetical order.

An example:

const array = [];

function adicionar() {
  array.push($("#novo").val());
  
  $("#Brand").children('option').each(function() {
    $('#Brand').html('');
    array.sort();
    array.forEach(function(item) {
      $('#Brand').append('<option value="' + item + '">' + item + '</option>');
    });
  });
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="Brand">
  <option />
</select>

<br>
<input id="novo" />
<button onclick="adicionar()">Adicionar</button>
    
19.12.2016 / 22:00
4

You can create a function to do this and call after append() . This question has several examples of how to do this.

function OrdenarSelect() {
  var selElem = document.getElementById('EquipmentTypelID');
  var tmpAry = new Array();
  for (var i = 0; i < selElem.options.length; i++) {
    tmpAry[i] = new Array();
    tmpAry[i][0] = selElem.options[i].text;
    tmpAry[i][1] = selElem.options[i].value;
  }
  tmpAry.sort();
  while (selElem.options.length > 0) {
    selElem.options[0] = null;
  }
  for (var i = 0; i < tmpAry.length; i++) {
    var op = new Option(tmpAry[i][0], tmpAry[i][1]);
    selElem.options[i] = op;
  }
  return;
}
<button type="button" onclick="OrdenarSelect()">Ordenar</button>
<select id="EquipmentTypelID">
  <option value='22'>Opção 4</option>
  <option value='101'>Opção 2</option>
  <option value='1'>Opção 3</option>
  <option value='-2'>Opção 1</option>
</select>

To use in your code, just call the function by passing it after inserting the element with .append() , like this:

success: function (data) {
    if (data.Name == name) {
        alert("A mcarca " + name + " foi cadastrado com sucesso!");
        $('#Brand').append('<option value="' + data.BrandID + '">' + data.Name + '</option>');
         OrdenarSelect(); //Função aqui
    } else if (data == false) {
        alert("Não foi possível cadastrar a marca " + name + "!");
    } else {
        alert("A marca " + data.Name + " já está cadastrada");
    }
}

Another option, which guarantees validation in server , is to return a PartialView with all DropDownList and just replace. Depending on the amount of items, it can be a good or bad option. But it all depends on your context.

Read tips:

19.12.2016 / 21:59