Click on button does not work

Asked

Viewed 25 times

0

I’m not getting the Remove button to work at all. I run it dynamically through jquery, but at the time of removing the not button from any reply. Nor does the console message appear...

var pares = 0;

$("#codigo_barras").keydown(function(e){
    if(e.which===13){
      var codigo = $(this).val();
      var linha = $("<div>").addClass("row p-1 bordaCodigo");
      var colunaCodigo = $("<div>").addClass("col-sm-2").text(codigo);
      var botaoRemover = $("<button>").addClass("remover btn btn-danger").append("<span class='fa fa-times'>X</span>");
      var colunaRemover = $("<div>").addClass("col-sm-1");
      colunaRemover.append(botaoRemover);
      linha.append(colunaRemover);
      linha.append(colunaCodigo);
      $(".codigos").append(linha);

      pares++;
      $(".pares").text(pares);
    }   
});

$(".remover").on("click",function(){
  console.log("teste");
  var linha = $(this).parent().parent();
  linha.remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input id="codigo_barras">
<div class="codigos"></div>

1 answer

2


The problem is that when the code

$(".remover").on("click",function(){
  console.log("teste");
  var linha = $(this).parent().parent();
  linha.remove();
});

No element is executed .remover exists in the DOM and thus none of them will receive the event click. Instead, add the event to the parent element and verify that the event was generated from a .remover son.

$(".codigos").on("click", ".remover", function(){
  console.log("teste");
  var linha = $(this).parent().parent();
  linha.remove();
});

So the event will be associated with the element .codigos, which already exists in the DOM, but will be fired only when starting from a child .remover.

var pares = 0;

$("#codigo_barras").keydown(function(e){
    if(e.which===13){
      var codigo = $(this).val();
      var linha = $("<div>").addClass("row p-1 bordaCodigo");
      var colunaCodigo = $("<div>").addClass("col-sm-2").text(codigo);
      var botaoRemover = $("<button>").addClass("remover btn btn-danger").append("<span class='fa fa-times'>X</span>");
      var colunaRemover = $("<div>").addClass("col-sm-1");
      colunaRemover.append(botaoRemover);
      linha.append(colunaRemover);
      linha.append(colunaCodigo);
      $(".codigos").append(linha);

      pares++;
      $(".pares").text(pares);
    }   
});

$(".codigos").on("click", ".remover", function(){
  console.log("teste");
  var linha = $(this).parent().parent();
  linha.remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Digite um <input placeholder="Código de Barras" id="codigo_barras"> e pressione <kbd>Enter</kbd>
<div class="codigos"></div>

  • That’s right. Thanks friend.

Browser other questions tagged

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