Bill Kindig
Bill Kindig

Reputation: 3652

Why does jQuery on change event fire multiple times?

I am trying to bind event handlers to dynamically added <select> elements. But the event is firing 1 extra time for each time the select list changes. (First time it fires once, then twice, then three times, etc.)

$(document).on('change', '.gender-select', function() {
  $('.gender-select').change(function() {
    alert($(this).find("option:selected").text());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<select class="gender-select">
  <option value="">- Select Gender -</option>
  <option value="m">Male</option>
  <option value="f">Female</option>
</select>

https://jsfiddle.net/L3p9ez5d/3/

Solution

Thanks, Rory McCrossan, for your answer. Quite simple, I had a static event handler inside of a delegated one, so handlers kept getting added when the delegated handler fired.

Upvotes: 2

Views: 2289

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337637

The reason is because you are nesting your event handlers. You've placed a static event handler within a delegated one, so each time an event happens another handler is added. This is also the reason why nothing happens when you first select an option.

To fix the problem simply remove the inner static event handler:

$(document).on('change', '.gender-select', function() {
  console.log($(this).find("option:selected").text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<select class="gender-select">
  <option value="">- Select Gender -</option>
  <option value="m">Male</option>
  <option value="f">Female</option>
</select>

Upvotes: 4

Related Questions