How to remove a <TR> element from a list created with append?

Asked

Viewed 876 times

2

[PERSONAL RESOLUTION]

var precoFinal = 0;
       		
       	
            // função botão para adicionar um produto a um pedido    
			$('#botao').on('click', function(event){
			event.preventDefault();
			
			var codigo = $('#inputCodigo').val();
			var descricao = $('#inputDescricao').val();
			var estoque = $('#inputEstoque').val();
			var precoVenda = $('#inputPreco').val();
			var quantidade = $('#inputQuantidade').val();
			var precoTotal = quantidade * precoVenda;
		

			if (codigo != '') {
			$('#tabela').append('<tr>'+'<td>'+codigo+'</td>'+'<td>'+descricao+'</td>'+'<td>'+quantidade+'</td>'+
			'<td>'+precoVenda+'</td>'+'<td>'+precoTotal+'</td>'+'<td>'+'<button type="button" class="btn btn-danger">EXCLUIR</button>'+'</td>'+'</tr>')
			
			}
			
			$('#inputCodigo,#inputDescricao,#inputEstoque,#inputPreco,#inputQuantidade').val('');


			precoFinal += precoTotal;

			 $('#totalPedido').html("TOTAL DO PEDIDO: " + precoFinal);

			
			 
		});//final da função adicionar produto ao pedido

		$('#tabela').on('click','.btn', function(){
			$(this).closest('tr').remove();
		})			

  • 1

    "(...) are the same element , same ID (...)" If you have elements with the same id is already technically incorrect.

  • @Francomartins, delete your answer... that content should be posted in your question.

  • Guys are doing a test here , and thinking it best I store the data of the items in an object and from there

  • @Francomartins share your solution to the question, it can be a solution for other people

  • Rafael, how do I do it??

3 answers

1

I made a very practical example, see if it solves your problem. Remembering that you can change indicating tr by class, id, position, etc... just modify for your needs.

I modified the code, now you can delete by index0 and check marked.

$('#removerTrIndex').click(function() {
  if ($('tr')[0]) {
    $($('tr')[0]).remove();
  } else {
    alert('Não existe mais TR');
  }
});

$('#removerTrMarcada').click(function() {
  $('input').each(function(e,inp) {
    if ($(inp).is(':checked')) {
      $(inp).parent().parent().remove();
    }
  });
});
input[type=checkbox] {
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td><input type="checkbox"></input>Oi</td>
    </tr>
    <tr>
      <td><input type="checkbox"></input>Oi</td>
    </tr>
    <tr>
      <td><input type="checkbox"></input>Oi</td>
    </tr>
    <tr>
      <td><input type="checkbox"></input>Oi</td>
    </tr>
  </tbody>
</table>
<button id="removerTrIndex">Remover tr index</button>
<button id="removerTrMarcada">Remover tr marcada</button>

  • Does Matthew speak all good friend?? then , this example of yours will remove the TR in Dice [0], but what if the customer wants to remove the item that is in Dice [4]? Thanks for the help

  • Oops, all right, I’ll modify the code and meet your need.

  • Ready @Francomartins now added a check that if checked it removes tr.

  • Matthew Thanks , can not delete by the same button ne? After all all the TR and TD will have everything the same and it is difficult to make the button understand which one has to delete, but this will help me to solve the problem.

  • Calm @Francomartins everything is possible, you have to identify which you want to delete, it can be an input where it will put the number of tr or it can be the checkbox, or you can pick according to the data of tr, need your scenario to help you.

1

You can use the deleteRow() see an example:

function deletaRow(index){
  document.getElementById('tbody').deleteRow(index);
}

function adicionaLinha(){
  var tbody = document.getElementById('tbody');

  var tr = document.createElement('tr');
  tr.onclick = function(){
    deletaRow(this.rowIndex-1)
  }


  var td = document.createElement('td');
  td.innerText = tbody.rows.length + 1;

  tr.appendChild(td);
  tbody.appendChild(tr);

}
<table>
  <thead>
    <tr >
      <th >#ID</th>
    </tr>
  </thead>
  <tbody id="tbody">
    <tr onclick="deletaRow(this.rowIndex-1)">
      <td>1</td>
    </tr>
    <tr onclick="deletaRow(this.rowIndex-1)">
      <td>2</td>
    </tr>
    <tr onclick="deletaRow(this.rowIndex-1)">
      <td>3</td>
    </tr>
    <tr onclick="deletaRow(this.rowIndex-1)">
      <td>4</td>
    </tr>
  </tbody>
</table>
<button onclick="deletaRow(0)">Remover Primeira</button>
<button onclick="adicionaLinha()">Adicionar</button>

EDIT To delete a specific without having an id you can add a function to each <tr> when created, when clicked calls another function to delete by passing as parameter its index obtained with this.rowIndex-1.

  • but if I want to remove item 4 or 3 and not item 1

  • I edited the code, click on any line.

0

First, you are using th instead of td, I changed your code a little and added the feature to remove the added tr.

var precoFinal = 0;
$('#botao').on('click', function(event){ event.preventDefault();
        
        //Trecho comentado apenas para a demonstração
        /*
        var codigo = $('#inputCodigo').val();
        var descricao = $('#inputDescricao').val();
        var estoque = $('#inputEstoque').val();
        var precoVenda = $('#inputPreco').val();
        var quantidade = $('#inputQuantidade').val();
        var precoTotal = quantidade * precoVenda;
        */
        
        //Alterado para valores fixos (demo)
        
        var codigo = "teste";
        var descricao = "descrição do produto";
        var estoque = 10;
        var precoVenda = 10.5;
        var quantidade = 5;
        var precoTotal = quantidade * precoVenda;

        if (codigo != ''){
        $('#tabela').append('<tr>'+'<td>'+codigo+'</td>'+'<td>'+descricao+'</td>'+'<td>'+quantidade+'</td>'+
        '<td>'+precoVenda+'</td>'+'<td>'+precoTotal+'</td>'+'<td class="btn btn-danger excluir"  onclick="removerProduto(this);">EXCLUIR</td>'+'</tr>');

        }

        $('#inputCodigo,#inputDescricao,#inputEstoque,#inputPreco,#inputQuantidade').val('');


        precoFinal += precoTotal;

         $('#totalPedido').html("TOTAL DO PEDIDO: " + precoFinal);

         
});

var removerProduto = (function(elemento){  
  $(elemento).closest('tr').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html lang="en">
  <head>
    <title>Hello, world!</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" type="text/css" href="css/estilo.css">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
  </head>
  <body>
  <div class="container">
  <h1 align="center" class="mt-5">PEDIDO DE VENDA</h1>  
    <form id="formulario">
        <div class="row">
            <div class="form-group col-md-1">
              <label for="inputCodigoVendedor">CODIGO</label>
              <input type="text" class="form-control" id="inputCodigoVendedor" name="codigoVendedor">
            </div>
            <div class="form-group col-md-5">
              <label for="inputVendedor">VENDEDOR</label>
              <input type="text" class="form-control text-uppercase" id="inputvendedor" name="vendedor">
              <div id="divVendedor"></div>
            </div>
            <div class="form-group col-md-1">
              <label for="inputCodigoCliente">CODIGO</label>
              <input type="text" class="form-control" id="inputCodigoCliente" name="codigoCliente">
            </div>
            <div class="form-group col-md-5">
              <label for="inputCliente">CLIENTE</label>
              <input type="text" class="form-control text-uppercase" id="inputCliente" name="cliente">
              <div id="divCliente"></div>
            </div>
        </div>
        <div class="row">
            <div class="form-group col-md-1">
              <label for="inputCodigo">CODIGO</label>
              <input type="text" class="form-control" id="inputCodigo" name="codigo">
            </div>
            <div class="form-group col-md-6">
              <label for="inputDescricao">DESCRIÇÃO</label>
              <input type="text" class="form-control text-uppercase" id="inputDescricao" name="descricao">
              <div id="response"></div>
            </div>
            <div class="form-group col-md-1">
              <label for="inputEstoque">ESTOQUE</label>
              <input type="text" class="form-control" id="inputEstoque" name="estoque">
            </div>
            <div class="form-group col-md-2">
              <label for="inputQuantidade">QUANTIDADE</label>
              <input type="text" class="form-control" id="inputQuantidade" name="quantidade">
            </div>
            <div class="form-group col-md-2">
              <label for="inputPreco">PREÇO</label>
              <input type="text" class="form-control" id="inputPreco" name="preco">
            </div>
        </div>
      </form>
     <button class="btn btn-success mt-3" type="submit" id="botao">ADICIONAR PRODUTO</button>
     <div class="mt-3">
      <table class="table table-striped" id="tabela">
      <thead class="thead-dark">
        <tr>
          <th scope="col">CODIGO</th>
          <th scope="col">DESCRIÇÃO</th>
          <th scope="col">QUANTIDADE</th>
          <th scope="col">PREÇO UN</th>
          <th scope="col">PREÇO TOTAL</th>
          <th scope="col">AÇÃO</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
    <span id="totalPedido"></span>
</div>   
  </div>
      <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
    <script type="text/javascript" src="js/main1.js"></script>
  </body>
</html>

  • thanks for the answer, to find this error ai Uncaught Referenceerror: removerProduto is not defined at Htmltablecellelement.onclick ((index):1) onclick @ (index):1, I left the code as well as yours , just removed that HTML input to add

  • Edit and put in your question your html and js

  • Leandro Angelo now yes I got kkkkk, ta the whole HTML up there and the JS code snippet

  • I realized here that when gives the mistake he send me la pro sources, there really does not exist the TR , but in Elements yes

Browser other questions tagged

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