How do I change the position of two names in the table using up and down buttons?

Asked

Viewed 31 times

-1

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Exemplo de Paginação</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>
  <script>
    let lsAlunos = ["Alef Mourão dos Santos", "Andre Alex", "Danilo Rodrigues Soares", "Dhiego de Sampaio", "Emerson de Ferto", "Gabriel de Oliveira ", "Jhoune Souza Justino", "Josef Gildevan Santos", "João Santos Chagas", "Julio Lima", "Jônatas Maciel", "Loren Muniz Ferreira", "Luna Cavalcante", "Marcos Silva", "Marcos Barbosa da Silva", "Tais Pereira Melo", "Yudi Medeiros Santos", "Marco Pereira Silva"];


    pgAtual = 0;

    function carregarTabela(pg) {
      tamanhoArray = Math.ceil((lsAlunos.length) / 5);
      if (pg <= 0 || pg > tamanhoArray) {
        return;
      }

      pgAtual = pg;
      fim = (pg * 5);
      inicio = fim - 5;
      txLinhas = "";
      for (i = inicio; i < fim; i++) {
        if (lsAlunos[i] == undefined) break;
        txLinhas += `<tr><td>${Number(i) + 1}</td><td>${lsAlunos[i]}</td></tr>`;
      }
      document.getElementById("corpoTabela").innerHTML = txLinhas;
      itemLista = document.getElementById("pg-" + pg);
      itemLista.classList.add("active");

      antigo = document.getElementById("pgAT");
      if (antigo.value != '') {
        itemLista = document.getElementById("pg-" + antigo.value);
        itemLista.classList.remove("active");
      }
      antigo.value = pg;
    }

    function mudarPagina(pg) {
      carregarTabela(pgAtual + pg);
    }
  </script>

  <input type="hidden" value="" id="pgAT">
  <table class="table table-striped">
    <thead>
      <tr>
        <th>
          Linha
        </th>
        <th>
          Nome dos Alunos
        </th>
      </tr>
    </thead>
    <tbody id="corpoTabela">
    </tbody>
  </table>
  <ul class="pagination justify-content-center" id="paginacao">



  </ul>
  <script>
    lsPagina = `<li class="page-item"><a class="page-link" href="#" onclick="carregarTabela(document.getElementById('pgAT').value -1)">Anterior</a></li>`
    tamanhoArray = Math.ceil((lsAlunos.length) / 5);
    for (i = 0; i < tamanhoArray; i++) {
      lsPagina += `<li id='pg-${Number(i)+1}' class="page-item"><a class="page-link" href="#" onclick="carregarTabela(${Number(i)+1})">${Number(i)+1}</a></li>`
    }
    lsPagina += `<li class="page-item"><a class="page-link" href="#" onclick="carregarTabela(Number(document.getElementById('pgAT').value) +1)">Próximo</a></li>`;
    document.getElementById("paginacao").innerHTML = lsPagina;
    carregarTabela(1);
  </script>
</body>

</html>

1 answer

3

Basically you need to find the reference of the TR, because you want to move the whole line, then find the reference of the previous or next line and move the TR.

If you have a button, it will be somewhere inside the TR, so if you have the button reference, you can use the parentNode to get the "parent" element reference. In the example below, I added the buttons in a new TD, so you need to use .parentNode twice, because once it will return TD, which is the "father" where the button is, and the second the TR, which is the "father" of the TD. I also added below a Function that receives by parameter the button with this and the order, which I used -1 to previous and 1 to next.

From there, you need to decide whether to move up or down. Up would be the previous element, which we can get using previousSibling, that will return the anther node on the "same level" of the DOM, that is to say the previous TR, and for the following element we can use nextSibling.

Finally, to move the element we must insert the TR in question before or after the "brother element" (sibling), for this we can use before() or after(), respectively. Below a code demonstrating:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<body>
  <script>
    let lsAlunos = ["Alef Mourão dos Santos", "Andre Alex", "Danilo Rodrigues Soares", "Dhiego de Sampaio", "Emerson de Ferto", "Gabriel de Oliveira ", "Jhoune Souza Justino", "Josef Gildevan Santos", "João Santos Chagas", "Julio Lima", "Jônatas Maciel", "Loren Muniz Ferreira", "Luna Cavalcante", "Marcos Silva", "Marcos Barbosa da Silva", "Tais Pereira Melo", "Yudi Medeiros Santos", "Marco Pereira Silva"];


    pgAtual = 0;

    function carregarTabela(pg) {
      tamanhoArray = Math.ceil((lsAlunos.length) / 5);
      if (pg <= 0 || pg > tamanhoArray) {
        return;
      }

      pgAtual = pg;
      fim = (pg * 5);
      inicio = fim - 5;
      txLinhas = "";
      // aqui cria um par de botões, pode usar qualquer elemento que quiser e aplicar estilo
      var ordenador = "<td><button onclick='ordenar(this,-1)'>Cima</button><button onclick='ordenar(this,1)'>Baixo</button></td>"
      
      for (i = inicio; i < fim; i++) {
        if (lsAlunos[i] == undefined) break;
        txLinhas += `<tr><td>${Number(i) + 1}</td><td>${lsAlunos[i]}</td>` + ordenador + `</tr>`;
      }
      document.getElementById("corpoTabela").innerHTML = txLinhas;
      itemLista = document.getElementById("pg-" + pg);
      itemLista.classList.add("active");

      antigo = document.getElementById("pgAT");
      if (antigo.value != '') {
        itemLista = document.getElementById("pg-" + antigo.value);
        itemLista.classList.remove("active");
      }
      antigo.value = pg;
    }

    function mudarPagina(pg) {
      carregarTabela(pgAtual + pg);
    }
    
    function ordenar(btn, ordem) {
       //            BUTTON  TD      TR
       //  trAtual ir apontar para a TR de onde foi clicado o botão
       var trAtual = btn.parentNode.parentNode;
       
       // se for 1 é para baixo, então valida o nextSibling e insere depois (after)         
       if (ordem == 1 && trAtual.nextSibling != null) {
          trAtual.nextSibling.after(trAtual);
       // se for -1 é para cima, então valida o previousSibling e insere antes (before)         
       } else if (ordem == -1 && trAtual.previousSibling != null) {
         trAtual.previousSibling.before(trAtual);
       }
    }
    
  </script>

  <input type="hidden" value="" id="pgAT">
  <table class="table table-striped">
    <thead>
      <tr>
        <th>
          Linha
        </th>
        <th>
          Nome dos Alunos
        </th>
        <th>Ordenar</th>
      </tr>
    </thead>
    <tbody id="corpoTabela">
    </tbody>
  </table>
  <ul class="pagination justify-content-center" id="paginacao">



  </ul>
  <script>
    lsPagina = `<li class="page-item"><a class="page-link" href="#" onclick="carregarTabela(document.getElementById('pgAT').value -1)">Anterior</a></li>`
    tamanhoArray = Math.ceil((lsAlunos.length) / 5);
    for (i = 0; i < tamanhoArray; i++) {
      lsPagina += `<li id='pg-${Number(i)+1}' class="page-item"><a class="page-link" href="#" onclick="carregarTabela(${Number(i)+1})">${Number(i)+1}</a></li>`
    }
    lsPagina += `<li class="page-item"><a class="page-link" href="#" onclick="carregarTabela(Number(document.getElementById('pgAT').value) +1)">Próximo</a></li>`;
    document.getElementById("paginacao").innerHTML = lsPagina;
    carregarTabela(1);
  </script>
</body>

Note that, I still saw if the previousSibling and the nextSibling are not null, this because it is a sibling element that has to be on the same level, the first and the last Trs will return null, because there are no more TR elements before or after.

Browser other questions tagged

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