Search code examples
jqueryjquery-select2jquery-select2-4

On select event for a cloned select2


What additional steps would I need to take in order to listen for the select2:select on a cloned select2?

I have tried .clone(true), $('.myclass').select2('destroy'); at the beginning of the click function, and refreshing DOM with $('#table tbody').hide().show(0);.

This appears to be the recommended way based on this GitHub issue.

https://github.com/select2/select2/issues/2522

$('.myclass').select2();

$('.myclass').on('select2:select', function(e) {
	alert('foo');
});

$('#addRow').click(function() {
  $('#table tbody').append($('#table tbody tr:last').clone());
  $('#table tbody tr:nth-last-child(2) select').addClass('myclass');
  $('.myclass').select2();  
});
.hidden {
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
<table id="table">
 <thead></thead>
 <tbody>
   <tr>
     <td>
      <select class="myclass">
        <option>1</option>
        <option>2</option>
        <option>3</option>
      </select> 
     </td>
   </tr>
   <tr>
     <td>
       <select id="clone" class="hidden">
        <option>1</option>
        <option>2</option>
        <option>3</option>
       </select>
     </td>
   </tr>
 </tbody>
 <tfoot>
  <button id="addRow">
    Add Row 
  </button>
 </tfoot>
</table>


Solution

  • You can do event delegation to bind events to dynamically added elements.

    $('.myclass').select2();
    
    $(document).on('select2:select','.myclass', function(e) {
    	alert('foo');
    });
    
    $('#addRow').click(function() {
      $('#table tbody').append($('#table tbody tr:last').clone());
      $('#table tbody tr:nth-last-child(2) select').addClass('myclass');
      $('.myclass').select2();  
    });
    .hidden {
      display:none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
    <table id="table">
     <thead></thead>
     <tbody>
       <tr>
         <td>
          <select class="myclass">
            <option>1</option>
            <option>2</option>
            <option>3</option>
          </select> 
         </td>
       </tr>
       <tr>
         <td>
           <select id="clone" class="hidden">
            <option>1</option>
            <option>2</option>
            <option>3</option>
           </select>
         </td>
       </tr>
     </tbody>
     <tfoot>
      <button id="addRow">
        Add Row 
      </button>
     </tfoot>
    </table>