Didina Deen Didina Deen - 1 month ago 7
HTML Question

jQuery on click event firing multiple times

I just learned how to use the method .on() and I use it to add an event handler to some buttons that are added "live" (after the DOM is ready).

$('#table').on("click", ".delete", function() {
//whatever
});


This seems to work fine but when I use it in my code I get the click event fired twice. It fires as many times as I have changed the selector, that is, I click a name in the selector and then another and another, let's say 3 times, then when clicking the mentioned button I will get an alert with all those 3 names instead of only the one is selected at that time.

I haven't been able to replicate it in a JsFiddle as the whole thing is quite big. So let me know what else I can add to make the question better.

JS

$('#dataSelector').change(function() {
#more code
$('#table').on("click", ".delete", function() {
var data_name = $("#dataSelector option:selected").attr('name');
alert(data_name);
});
});


HTML

<div id="selectData">
<label>Select:</label>
<br>
<div class="">

<select id="dataSelector" class="form-control">

<option id="default" selected="true" name="default">Pick</option>

<option value="1" name="somethingA">somethingA</option>

<option value="2" name="somethingB">somethingB</option>

<option value="3" name="somethingC">somethingC</option>

</select>


</div>
</div>

<div id="goal_table" class="col-md-12">

<table id="table" class="table table-bordered">
<tbody>
<tr>
<th>Name1</th>
<th>Name2</th>
<th>Name3</th>
<th>name4</th>
<th></th>
</tr>
<tr id="13">
<td>somethingA</td>
<td>value</td>
<td>whatever</td>
<td>∞</td>
<td>
<button name="13" type="button" class="btn btn-default delete"><i class="fa fa-trash" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>

</div>

Answer

just add off() before on() to remove existing event on it

there's a possibility that you already bind an event in that element so if you want to rebind the event you just off('event') to avoid firing event multiple times

$('#table').off("click").on("click", ".delete", function() {
    var data_name = $("#dataSelector option:selected").attr('name');
    alert(data_name);
});