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
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>