A continuación se muestra mi código, al hacer clic en el botón Agregar a mi tabla, mi pregunta es, ¿hay formas de ordenar la tabla según ItemId después de 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);Edite, vea la captura de pantalla a continuación sobre lo que quiero lograr: quiero que mi tabla se ordene por la columna resaltada, ¿hay alguna forma de ordenar la tabla completa después de hacer clic en agregar/editar?
Puede usar los métodos append , prepend y after para mover los nodos.
https://developer.mozilla.org/en-US/docs/Web/API/Element/append
Pseudocódigo para vainilla javascript:
document.getElementById("yourTableIdOrTbody").append(document.getElementById("yourTrToMOveToTheEnd")); document.getElementById("yourTableIdOrTbody").prepend(document.getElementById("yourTrToMOveToTheBegin")); document.getElementById("trIdBase").after(document.getElementById("yourTrToMOveToAfterTrBase"));Para JQuery ( https://api.jquery.com/after/ ):
$("#yourTableIdOrTbody").append($("#yourTrToMOveToTheEnd")); $("#yourTableIdOrTbody").prepend($("#yourTrToMOveToTheBegin")); $("#trIdBase").after($("#yourTrToMOveToAfterTrBase"));Por supuesto, no necesita tener las identificaciones para que coincidan con los nodos. Puede buscar los nodos de cualquier otra forma.
Dado que agrega algo llamado tblItemList , asumo que desea ordenar una estructura de datos y no elementos reales.
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> Tenga en cuenta que usa la misma id varias veces, lo que provoca un HTML no válido. Sin embargo, el problema tiene solución, pero es posible que también desee solucionarlo.
En jQuery puede separar , ordenar y agregar elementos para reordenarlos.
Como se mencionó en las otras respuestas, dar a los elementos identificaciones idénticas causará problemas, aunque puede solucionarlo fácilmente usando class es en su lugar.
Aquí un código de muestra:
$('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>