Didina Deen Didina Deen - 1 year ago 62
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() {

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.


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


<div id="selectData">
<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>



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

<table id="table" class="table table-bordered">
<tr id="13">
<button name="13" type="button" class="btn btn-default delete"><i class="fa fa-trash" aria-hidden="true"></i>


Answer Source

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download