Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Maneju

[Resolvido] Remover Linhas de Table

Recommended Posts

Olá.

 

Estou usando o exemplo abaixo para criar linhas na Table com um botão:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script language="javascript">
      function inserirLinhaTabela() {
            // Captura a referência da tabela com id “minhaTabela”
            var table = document.getElementById("minhaTabela");
            // Captura a quantidade de linhas já existentes na tabela
            var numOfRows = table.rows.length;
            // Captura a quantidade de colunas da última linha da tabela
            var numOfCols = table.rows[numOfRows-1].cells.length;
            // Insere uma linha no fim da tabela.
            var newRow = table.insertRow(numOfRows);
 
            // Faz um loop para criar as colunas
            for (var j = 0; j < numOfCols; j++) {
                // Insere uma coluna na nova linha 
                newCell = newRow.insertCell(j);
                // Insere um conteúdo na coluna
                newCell.innerHTML = "Linha "+ numOfRows + " – Coluna "+ j;				
            }
        } 
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
  <input name="button" type="button" onclick="inserirLinhaTabela()" value="Inserir Linha"  />
</form>
<form id="form2" name="form2" method="post" action="">
				
				<table id="minhaTabela" border="1">
            <tr>
                <td>
                    Linha 0 - Coluna 0
                </td>
                <td>
                    Linha 0 - Coluna 1
                </td>
            </tr>
        </table>
        
</form>
<p> </p>
</body>
</html>

 

Sei que o comando abaixo remove linhas da Table:

 

document.getElementById('myTable').deleteRow(i)

 

Minha dificuldade está em identificar qual a linha que o usuário deseja deletar. Teria por exemplo, jeito de colocar um botão EXCLUIR por linha da table e assim que clicasse nele faria o deleteRow correspondente?

 

Grato!

Compartilhar este post


Link para o post
Compartilhar em outros sites

Sim no Tr, você coloca id=1 e no outro id=2 e no outro id=3 e assim vai.

dae você manda o if na funcao e coloca dentro do document.getElementById(id)

 

 

<tr id='1' onClick='deletaLinha(this.id)'>

Dae na funcao,

function deletaLinha(id){
   document.getElementById('myTable').deleteRow(id)
}

É soh uma ideia, nem tinha visto isso ainda.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá.

 

Mas este comando abaixo não teria que ser feito em JS para funcionar? Eu queria que na frente da última coluna, ficasse um botão excluir.

<tr id='1' onclick='deletaLinha(this.id)'>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Veja:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script language="javascript">
      function inserirLinhaTabela() {
            // Captura a referência da tabela com id “minhaTabela”
            var table = document.getElementById("minhaTabela");
            // Captura a quantidade de linhas já existentes na tabela
            var numOfRows = table.rows.length;
            // Captura a quantidade de colunas da última linha da tabela
            var numOfCols = table.rows[numOfRows-1].cells.length;
            // Insere uma linha no fim da tabela.
            var newRow = table.insertRow(numOfRows);
 
            // Faz um loop para criar as colunas
            for (var j = 0; j < numOfCols; j++) {
                // Insere uma coluna na nova linha 
                newCell = newRow.insertCell(j);
                // Insere um conteúdo na coluna
                newCell.innerHTML = "Linha "+ numOfRows + " – Coluna "+ j + "<a href='#' onClick='deleta("+numOfRows+")'> - Excluir</a>";
            }
        } 
		function deleta(id){
			document.getElementById("minhaTabela").deleteRow(id);
		}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
  <input name="button" type="button" onclick="inserirLinhaTabela()" value="Inserir Linha"  />
</form>
<form id="form2" name="form2" method="post" action="">
                                
        <table id="minhaTabela" border="1">
            <tr>
                <td>
                    Linha 0 - Coluna 0
                </td>
                <td>
                    Linha 0 - Coluna 1
                </td>
            </tr>
        </table>
        
</form>
<p> </p>
</body>
</html>

Coloquei minha ideia em pratica.

Deu certo. =)

Compartilhar este post


Link para o post
Compartilhar em outros sites

Perfeito, era isso mesmo!

 

Thanks!

 

PS - só tem que corrigir os IDs depois que houver uma exclusão senão vai excluir linha errada....

Compartilhar este post


Link para o post
Compartilhar em outros sites

Só uma dúvida...

 

Qdo excluir uma linha eu consigo mudar o valor do onclick (onclick='deleta("+numOfRows+")'>)? Ou vou ter que criar uma nova coluna para controlar a numeração da linha qdo houver exclusão/inclusão?

 

Ps - não consegui "pegar" o conteúdo de uma célula, como se faz?

 

Tem uma falha aqui, só funciona se eu excluir sempre a última linha. Qualquer outra linha excluída que não seja a última, quebrará a "amarração" entre a posição da tabela e o conteúdo de "<a href='#' onclick='deleta("+numOfRows+")'>:

 

 

Supondo ter 3 linhas na Table:

newCell.innerHTML = "Linha "+ numOfRows + " – Coluna "+ j + "<a href='#' onclick='deleta("1")'> - Excluir</a>";
newCell.innerHTML = "Linha "+ numOfRows + " – Coluna "+ j + "<a href='#' onclick='deleta("2")'> - Excluir</a>";
newCell.innerHTML = "Linha "+ numOfRows + " – Coluna "+ j + "<a href='#' onclick='deleta("3")'> - Excluir</a>"

Se excluir a segunda linha, ficará assim:

newCell.innerHTML = "Linha "+ numOfRows + " – Coluna "+ j + "<a href='#' onclick='deleta("1")'> - Excluir</a>";
newCell.innerHTML = "Linha "+ numOfRows + " – Coluna "+ j + "<a href='#' onclick='deleta("3")'> - Excluir</a>";

Aí já perdi o controle, pois a antiga linha 3 está atrelada ao ID 2, assim sendo nada será excluído.

 

Tem como fazer um laço FOR alterando só este fragmento "<a href='#' onclick='deleta("+numOfRows+")'> toda vez que que a function deleta for executada?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá.

 

Acabei resolvendo com esta rotina, onde pode-se excluir várias linhas (tem um checkbox de seleção para cada linha) em um clique único no botão e não dá os problemas mencionados na rotina anterior.

 

Rotina de Inlcusão de Linhas:

function addRow(tableID) {
     var table = document.getElementById(tableID);
     var rowCount = table.rows.length;
     var row = table.insertRow(rowCount);
 
     var cell1 = row.insertCell(0);
     var element1 = document.createElement("input");
     element1.type = "checkbox";
     cell1.appendChild(element1);

     var cell3 = row.insertCell(1);
	 cell3.innerHTML = $("#codprod").val();

     var cell4 = row.insertCell(2);
	 cell4.innerHTML = $("#produto").val();
	 
     var cell5 = row.insertCell(3);
	 cell5.innerHTML = $("#qtde").val();

     var cell6 = row.insertCell(4);
	 cell6.innerHTML = $("#bruto").val();

     var cell7 = row.insertCell(5);
	 cell7.innerHTML = $("#desc").val();
	 
	 var cell8 = row.insertCell(6);
	 cell8.innerHTML = $("#liquido").val();
	 
	 var cell9 = row.insertCell(7);
	 cell9.innerHTML = $("#aliquota").val();
	 
	 var cell10 = row.insertCell(8);
	 cell10.innerHTML = $("#total").val();
}

Rotina de Exclusão de Linhas:

function deleteRow(tableID) {
   try {
      var table = document.getElementById(tableID);
      var rowCount = table.rows.length;
      for(var i=0; i<rowCount; i++) {
           var row = table.rows[i];
           var chkbox = row.cells[0].childNodes[0];
           if(null != chkbox && true == chkbox.checked) {
                table.deleteRow(i);
                rowCount--;
                i--;
           }
      }
      }catch(e) {
         alert(e);
      }
}

 

Botão que Executa a Inclusão:

<input name="button" type="button" onclick="addRow('minhaTabela')" id="btndigitar" value="Lançar"  />

 

Botão que Executa a Exclusão:

<input name="button2" type="button" onclick="deleteRow('minhaTabela')" id="btndeletar" value="Excluir"  />

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.