Sort Dropdown with jquery after append

Asked

Viewed 646 times

3

In case the user does not find the desired item in the list of dropdown, it can include a new item, for this I used the function promptof javascript, and then the user enters the name and click on Ok, If the object is not actually registered in the database(Sometimes due to lack of attention, and we do not find the item in the list), the object is registered. After registration the object is added to the list, but it goes to the end of it.

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

For this I thought of creating a script that would search the bank for all items (again)and be inserted again, but I think it is a waste of code. This is the script 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 Dropdownlist of View:

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

  • Why duplicate? I had already seen this question, but did not understand anything.

  • It is a possible duplicate, because the answers generated here will be similar to the one in the link question. However, this is just my opinion.

2 answers

4

You can create a function to do this and call after the 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, simply call the function by passing after inserting the element with the .append(), in this way:

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 ensures validation in server, is to return a PartialView with all the 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.

Reading tips:

  • how do I call the function after the append?

  • @Fabiosouza After that part $('#Brand').append('<option value="' + data.BrandID + '">' + data.Name + '</option>');, just put OrdenarSelect();. This is if you have done the function in the same way.

  • this row var selElem = Document.getElementById('Equipmenttypelid'); the id is from the list items or from the object (dropdown)?

  • @Fabiosouza instead of Equipmenttypelid you place your Dropdownlist ID

4

You can order save values of options in an array and then sort it. When only the .sort() without arguments, he already understands ascending and 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>

<select id="Brand">
  <option />
</select>

<br>
<input id="novo" />
<button onclick="adicionar()">Adicionar</button>

  • Array, in this case is the vector that is storing the right list of items? good in my case, as I will pull a list from the bank, and if it does not have the value will be entered, my array would have to bring the information from the right bank?

  • Array is the array variable. Actually not @Fabiosouza, when select is loaded by the database, it will have the contents.. this loop takes everything that is ALREADY inside, plus what has been inserted and orders. The only thing you will have to pay attention to is which attributes to fill inside the loop (like value, id, etc).

  • 1

    I think I get it. Later I’ll try... Thanks for now

  • array.push($("#novo").val()); this line would not be to add what to type in the array?

  • @Fabiosouza, yes, that’s right, so she’s out of the loop - after the addition is that the ordination is made.

Browser other questions tagged

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