Onilol Onilol - 6 months ago 18
jQuery Question

Handle firing multiple times

I have the following functions:

function isAdded(el){
if(!$(el).closest('tr').hasClass('cloned')){
$(el).closest('tr').addClass('cloned');
var row_variant_index = $("#items tbody tr.variant").index($(el).closest('tr'));
$(el).closest('tr').attr('data-index',row_variant_index);
var clone = $(el).closest('tr').clone(true);
clone.find('button').remove();
clone.find('td').last().prepend("<button name='delete'>x</button>"," ","<button name='decrement'>-</button>").append("<button name='increment'>+</button>");
clone.appendTo('#cloned-items tbody');
}
}

function handleButton(el){
var input_box = $(el).siblings('input');
switch ($(el).attr('name')){
case 'decrement':
if(parseInt($(input_box).val()) > 0){
$(input_box).val(parseInt($(input_box).val() - 1));
}
break;
case 'increment':
$(input_box).val(parseInt($(input_box).val() + 1));
break;
}
}


These functions are being used in this handle:

$("button[name='addItem']").click(function(){
if (!$(this).siblings('input').val().match(/\d+/)){
alert("You can only type numbers!");
return;
}
isAdded(this);
$("#cloned-items tbody").on('click',"button",function(){handleButton(this)});
});


My problem is that if I add more than 1 cloned item, the button begins adding or subtracting n+1 times ( If I have 2 clones it will add or subtract 2, if I have 3 it will add or subtract 3 and so on ).

Could someone tell me what am I doing wrong?

Answer

The reason is you are adding new event listener

$("#cloned-items tbody").on('click',"button",function(){handleButton(this)});

everytime you click the button

So you simply need to make sure you don't call it again after another click

Edit

As pointed out by @JeremyJStarcher you can use off() function to remove previously added handlers.

$("#cloned-items tbody").off().on('click',"button",function(){handleButton(this)});