Onilol Onilol - 11 months ago 41
jQuery Question

Handle firing multiple times

I have the following functions:

function isAdded(el){
var row_variant_index = $("#items tbody tr.variant").index($(el).closest('tr'));
var clone = $(el).closest('tr').clone(true);
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));
case 'increment':
$(input_box).val(parseInt($(input_box).val() + 1));

These functions are being used in this handle:

if (!$(this).siblings('input').val().match(/\d+/)){
alert("You can only type numbers!");
$("#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?


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


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)});