Table line deletion in Jquery

Asked

Viewed 101 times

1

I have a table with an delete button where it should, when clicked, 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 top line (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.

1 answer

1


Don’t use this inside that callback, jQuery changes the scope of that function and the this is the ajax object.

Besides $("#btExcluir") will always give the same element since Ids have to be unique.

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

$('.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);
      }
    });
  }
});
  • 1

    That’s exactly what it was, Sergio, thank you very much for the explanation !

Browser other questions tagged

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