Deleting Table Row in Jquery

1

I have a table with a delete button where it should be clicked to delete the record in question, but when I click delete it performs the correct deletion in the database and when updating the table it deletes the line from the top (previous record) on the front-end of the site.

//Insiro o botão na table com mais algumas infos

$('#tabela').append('<tr class="linha"><td align="center">' + $('#cbUnidadeOrigem option:selected').text() + '</td><td align="center">' + $('#unidade_destino option:selected').text() + '</td><td align="center" class="valCodBarras">' + txCdBarras.val() + '</td><td align="center">' + moment().format("DD/MM/YYYY HH:mm:ss") + '</td><td align="center"><a class="btn btn-danger btn-xs btExcluir" href="javascript:void(0)" rel=""><i class="icon-trash "></i></a></td></tr>');


//ajax para excluir o campo e limpar a table na linha

$('.btExcluir').on('click', function() {
  if (confirm('Deseja exluir este item?')) {


    jQuery.ajax({
      type: "GET", // HTTP method POST or GET
      url: "/malote/delMovMalote.php?id=" + $(this).attr('rel'),
      dataType: "text", // Data type, HTML, json etc.
      async: false,
      success: function(response) {
        $("#btExcluir").$(this).closest("tr").hide();
        countTabela = jQuery("#table tbody tr").length;
        countTabela--;
        $('#counter').html(countTabela);
      }
    });
  }
});

I know it's a simple mistake but I'm kind of lost in it.

    
asked by anonymous 20.06.2017 / 17:12

1 answer

1

Do not use this within this callback, jQuery changes the scope of this function and this is the ajax object.

In addition, so $("#btExcluir") will always give the same element since IDs must be unique.

You can create an alias and thus guarantee that .closest() uses the clicked button as the starting point:

$('.btExcluir').on('click', function() {
  var btn = this;
  if (confirm('Deseja exluir este item?')) {


    jQuery.ajax({
      type: "GET", // HTTP method POST or GET
      url: "/malote/delMovMalote.php?id=" + $(this).attr('rel'),
      dataType: "text", // Data type, HTML, json etc.
      async: false,
      success: function(response) {
        $(btn).closest("tr").hide();
        countTabela = jQuery("#table tbody tr").length;
        countTabela--;
        $('#counter').html(countTabela);
      }
    });
  }
});
    
20.06.2017 / 17:42