Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

91
Visualizações
How to make added element by jQuery knows recent functions

I have an html table each row (tr) have a value (exp: 200$) and a delete button, how to make each added row knows recent functions without recall them every time

$(function () {
    $('.add-prod').on("click", function (e) {
        $('#products_tbody').append('<tr >...</tr>');
        afterAddProd();
        change1();
        change2();
    });
    function afterAddProd() {
        ...
    };

    function change1() {
            ...
    }
    function change2() {
        ...
    }
}

cause when i delete a row the total of values will decrease three times for example

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here's an example of event delegation. You can set up a single delete function using jQuery's container.on(event, selector... that will work for any dynamically created button inside of a container. Here's an example

$(document).ready(function() {

  $('.added').on('click', 'button.del', function() {
    $(this).closest('.item').remove();
    tally()
  })

  $('button.add').click(function() {
    let n = $('.tpl').clone().removeAttr('hidden').removeClass('tpl').addClass('item');
    n.find('input.qty').val(Math.floor(Math.random() * 100));
    n.appendTo($('.added'))
    tally()

  })


  function tally() {
    let ttl = 0;
    $('.added input.qty').each(function() {
      ttl += +$(this).val()
    })
    $('.ttl').html(ttl)
  }


})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='add'>add</button>
<div class='added'>

</div>

<strong> total: <span class='ttl'></span></strong>

<div class='tpl' hidden>
  This is the new data <input type='number' class='qty' /> <button class='del'>delete</button>

</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda