2

 $('.add').on("click", function () {
        $('.selects').append('<select><option value="1">Added 1</option><option value="2">Added 2</option></select>');
      });
    
      $(".selects select").change(function () {
        alert("Success");
      });
 <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
 <div class="selects">
    <select>
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
 </div>
 <div class="add">
      Add Select
 </div>
   

The alert() that change in the appended select process does not work.

I'm waiting for your help with this.

Hitesh Tripathi
  • 856
  • 1
  • 11
  • 23
RedGRAP
  • 23
  • 3
  • Does this answer your question? [jQuery .live() vs .on() method for adding a click event after loading dynamic html](https://stackoverflow.com/questions/8752321/jquery-live-vs-on-method-for-adding-a-click-event-after-loading-dynamic-ht) – Medunoye Laxus Gbenga Dec 02 '19 at 09:22

1 Answers1

2

You need to do $(document).on('change','.selects select', function() {});. The reason you need to do that is because the DOM is added dynamically after the page has been loaded and since you want to listen for the change event for the dynamically generated element, you need to listen the change event from the document level for that select element.

$('.add').on("click", function() {
  $('.selects').append('<select><option value="1">Added 1</option><option value="2">Added 2</option></select>');
});

$(document).on('change','.selects select', function() {
  alert("Success");
});
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

<div class="selects">
  <select>
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
</div>

<div class="add">
  Add Select
</div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62