Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
Sort Table after Append jQuery/ Javascript

Below is my code, when clicking add button to my table, my question is, are there ways to sort the table based on ItemId after table.append?

    var ItemList = "<tr><td hidden id='ItemIdEdit'>" +
    ItemId +
    "</td><td id='ItemCodeEdit'>" +
    ItemCode +
    "</td><td style='text-align: right'>" +

    parseFloat(Quantity).toFixed(2) +
    "</td><td id='ItemUOM2'>" +


    ItemUOM +
    "</td><td hidden>" +
    LocationId +
    "</td><td>" +
    LocationCode +
    "</td><td style='text-align: right'>" +
    UnitCostParse +
    "</td><td style='text-align: right' >" +

    Total2 +
    "</td><td><div class='buttons'> <a href='#' class='btn btn-default btn-xs glyphicon glyphicon-edit' id='btnEdit'onclick='EditItem(this)'></div></td><td><div class='buttons'><a href='#' class='btn btn-default btn-xs glyphicon glyphicon-trash' id='btnAddToList'onclick='RemoveItem(this)'></a></div></td></tr>";

tblItemList.append(ItemList);

Edit, please see below screenshot on what I want to achieve: I want my table to be order by the highlighted column, are their any ways to sort the entire table after clicking add/edit?

enter image description here

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use the methods append, prepend and after to move the nodes.

https://developer.mozilla.org/en-US/docs/Web/API/Element/append

Pseudo code for vanilla javascript:

document.getElementById("yourTableIdOrTbody").append(document.getElementById("yourTrToMOveToTheEnd"));
document.getElementById("yourTableIdOrTbody").prepend(document.getElementById("yourTrToMOveToTheBegin"));
document.getElementById("trIdBase").after(document.getElementById("yourTrToMOveToAfterTrBase"));

For JQuery (https://api.jquery.com/after/):

$("#yourTableIdOrTbody").append($("#yourTrToMOveToTheEnd"));
$("#yourTableIdOrTbody").prepend($("#yourTrToMOveToTheBegin"));
$("#trIdBase").after($("#yourTrToMOveToAfterTrBase"));

Of course you don't need to have the id's to match the nodes. You can search the nodes using any other way.

about 4 years ago · Juan Pablo Isaza Relatório

0

Since you append to something called tblItemList, I assume you want to sort a data-structure and not actual elements.

    let tblItemList = [];
    var ItemList = "<tr><td hidden id='ItemIdEdit'>" +
    2 +
    "</td><td id='ItemCodeEdit'>" +
    2 +
    "</td><td style='text-align: right'>" +

    parseFloat(2).toFixed(2) +
    "</td><td id='ItemUOM2'>" +


    2 +
    "</td><td hidden>" +
    2 +
    "</td><td>" +
    2 +
    "</td><td style='text-align: right'>" +
    2 +
    "</td><td style='text-align: right' >" +

    2 +
    "</td><td><div class='buttons'> <a href='#' class='btn btn-default btn-xs glyphicon glyphicon-edit' id='btnEdit'onclick='EditItem(this)'></div></td><td><div class='buttons'><a href='#' class='btn btn-default btn-xs glyphicon glyphicon-trash' id='btnAddToList'onclick='RemoveItem(this)'></a></div></td></tr>";

tblItemList.push(ItemList);
    ItemList = "<tr><td hidden id='ItemIdEdit'>" +
    1 +
    "</td><td id='ItemCodeEdit'>" +
    2 +
    "</td><td style='text-align: right'>" +

    parseFloat(2).toFixed(2) +
    "</td><td id='ItemUOM2'>" +


    2 +
    "</td><td hidden>" +
    2 +
    "</td><td>" +
    2 +
    "</td><td style='text-align: right'>" +
    2 +
    "</td><td style='text-align: right' >" +

    2 +
    "</td><td><div class='buttons'> <a href='#' class='btn btn-default btn-xs glyphicon glyphicon-edit' id='btnEdit'onclick='EditItem(this)'></div></td><td><div class='buttons'><a href='#' class='btn btn-default btn-xs glyphicon glyphicon-trash' id='btnAddToList'onclick='RemoveItem(this)'></a></div></td></tr>";

tblItemList.push(ItemList);
for (let i = 0; i < tblItemList.length; i++) {
    for (let j = i + 1; j < tblItemList.length; j++) {
        let itemI = parseInt($(tblItemList[i]).find("#ItemIdEdit").text());
        let itemJ = parseInt($(tblItemList[j]).find("#ItemIdEdit").text());
        if (itemI > itemJ) {
            let aux = tblItemList[i];
            tblItemList[i] = tblItemList[j];
            tblItemList[j] = aux;
        }
    }
}

console.log(tblItemList);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Note that you use the same id multiple times, which causes invalid HTML. The issue is solvable though, but you might want to fix that as well.

about 4 years ago · Juan Pablo Isaza Relatório

0

In jQuery you can detach, sort and append to reorder elements.

As mentioned in the other answers, giving elements identical IDs will cause problems, although you can easily fix this by using classes instead.

Here some sample code:

$('button.add-item').on('click', function() {
  let item_id = (Math.random()+'').slice(-4);

  $('table').append(`
    <tr>
      <td class="item-id hidden">
        ${item_id}
      </td>
      <td class="item-code-edit">
        <input value="${item_id}" disabled>
      </td>
      <td class="item-cost align-right">
        ${parseFloat(Math.random() * 1000).toFixed(2)}
      </td>
      <td class="item-uofm">
        ItemUOM 
      </td>
      <td class="location-id hidden">
        LocationId
      </td>
      <td class="location-code">
        LocationCode
      </td>
      <td class="unit-cost-parse align-right">
        UnitCostParse
      </td>
      <td class="total align-right">
        Total2
      </td>
      <td>
        <div class="buttons">
          <button class="edit-item btn btn-default btn-xs glyphicon glyphicon-edit">EDIT</button>
          <button class="remove-item btn btn-default btn-xs glyphicon glyphicon-trash">REMOVE</button>
        </div>
      </td>
   </tr>`);
   
   //this is the code that does the re-ordering
   $('table').append($('table').find('tr').detach().sort((a, b) =>
     $(a).find('.item-id').text() - $(b).find('.item-id').text()));
 });
 
 $('table')
   .on('click', 'button.edit-item', function() {
     let $id_input = $(this).parents('tr').find('.item-code-edit input');
     $id_input.prop('disabled', !$id_input.prop('disabled'));
   })
   .on('click', 'button.remove-item', function() {
     $(this).parents('tr').remove();
 });
.align-right{
  text-align: right;}

.hidden{
  display: none;}
  
.item-code-edit input{
  width: 40px;}

table td{
  min-width: 64px;}
<button class="add-item">ADD ITEM</button>
<table></table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda