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

2

[SOLVED STAFF]

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();
		})			
    
asked by anonymous 20.12.2017 / 14:46

3 answers

1

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

I have modified the code, now you can delete it by index0 and checked check.

$('#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><inputtype="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>
    
20.12.2017 / 14:49
0

First, you're using th instead of td, I've changed your code a bit and added the function 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><!doctypehtml><htmllang="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>
    
20.12.2017 / 16:49
0

You can use deleteRow() to 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 one without having an id, you can add a function to every <tr> when created, which when clicked calls another function to delete by passing its index obtained with this.rowIndex-1 as a parameter.

    
20.12.2017 / 17:50