Home > Software design >  Attach Select2 with onClick() of jQuery
Attach Select2 with onClick() of jQuery

Time:12-19

I am trying to attach Select2 with onClick() of jQuery. My HTML code is <td id="47">Bob SMith and admin</td>. My jQuery code is like below.

(function($) {
    $(document).ready(function () {
        $(".volunteer").on("click", function () {            
        $(this).html(`<select  name="states[]" multiple="multiple">
                <option value="AL">Alabama</option>
                <option value="WY">Wyoming</option>
            </select>`);
        });
        $('.js-example-basic-multiple').select2();
    });
})(jQuery)

But this is not working.

CodePudding user response:

There are two issues preventing the select from loading.

  1. The initialisation of select2 is outside of the click event, it therefore occurs when the page loads before the select element exists. This must occur after the select has been added to the DOM.

    $('.js-example-basic-multiple').select2();
    
  2. The click event is registered on the class 'volunteer' and any clicks on the cell execute this function, even after the select is loaded. This causes the select to reload when you try and select an option, causing the option to be lost. To resolve this you could check if the select has already been loaded.

    if(!$(this).has("select").length) {
    

(function($) {
  $(document).ready(function() {
    var state = "";
    $(".volunteer").on("click", function(event) {
        // Check if select is already loaded
      if(!$(this).has("select").length) {
        // Populate select element
        $(this).html(`<select  name="states[]" multiple="multiple">
            <option value="AL">Alabama</option>
            <option value="WY">Wyoming</option>
            </select>`);      
              
        // Initialise select2
        $(this).children("select").select2();
      }
    });
  });
})(jQuery)
.js-example-basic-multiple {
  width: 200px;  
}

thead{
    font-weight: bold;
}

table, th, td {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />

<table>
  <thead>
    <tr>
      <td>Table Header 1</td>
      <td>Table Header 2</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td  id="47">Click Me</td>
      <td ></td>
    </tr>
    <tr>
      <td  id="48">Click Me</td>
      <td ></td>
    </tr>
  </tbody>
</table>

  • Related