Когда я создаю динамический c выпадающий с помощью select2, он ломается - PullRequest
0 голосов
/ 20 февраля 2020

У меня есть таблица с колонкой «жанр», в которой есть поле выбора, которое заполняется с помощью Select2, и у меня есть кнопка, которая добавляет новую строку в таблицу, как только я добавляю новую строку в таблицу, я попробуйте также заполнить жанр, используя select2, но он глючит, это приводит к тому, что новый выпадающий список не может быть выбран.

Взгляните на мой JSFiddle здесь: https://jsfiddle.net/hm3w7jtz/3/

Чтобы добраться до ошибки, добавьте новую группу, и вы заметите, что новый жанр строки недоступен для выбора.

https://jsfiddle.net/szjd6gu4/2/

Код

   <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
   </head>
   <h3> Movies </h3>
    <table class="my_table" id="movies" border="1px" style="border-collapse: collapse;">
    <thead>
      <tr><b>
        <td>Group</td>
        <td>Genre</td>
        <td>Movie Name</td>
        <td>Imdb</td>
        <td>Rotten Tomato</td>
        <td>Lead Actress</td>
        <td>Lead Actor</td>
        <td>Year of Release</td>
        <td>Revenue</td>
        <td>Budget</td>
      </tr></b>
    </thead>

    <tbody>
    <tr class="group-row">
    <td class="nr"><input type="text" placeholder="" size="9"><button id="btn" class="group" style="float:right;">+</button>
    </td>
    <td><select id="genre" class='genre' style="width:150px;"></select></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="10" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    </tr>
    </tbody>
  </table>
  <script>
    $(document).ready(function() {
    var genre = ['Action', 'Adventure', 'Fantasy', 'Anime', 'Romance'];
     $(".genre").select2({
        data: genre
      });
  });

  var row ="<td class='nr'><input type='text' placeholder='' size='9'><button id='btn' class='group' style='float:right;'>+</button></td><td><select id='genre' class='genre' style='width:150px;'></select></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='10' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td>";  


const $groupRow = $("<tr>", {
  class: "group-row"
}).append(row);

const tableBody = $("#movies tbody");
tableBody.on('click', '.group', (e) => {
  tableBody.append($groupRow.clone());
      $(".genre").select2({
        data: genre
      });
});
  </script>

1 Ответ

1 голос
/ 20 февраля 2020

Есть 2 проблемы с вашим кодом:

1) Удалите id = "genre" из обоих ваших выборов

<select id="genre" class='genre' style="width:150px;"></select>

2) Вам нужно переместить строку с массивом прямо перед функцией $ (document) .ready:

//BEFORE
    $(document).ready(function() {
    var genre = ['Action', 'Adventure', 'Fantasy', 'Anime', 'Romance'];
     $(".genre").select2({
        data: genre
      });
  });

//AFTER
var genre = ['Action', 'Adventure', 'Fantasy', 'Anime', 'Romance'];

$(document).ready(function() {            
         $(".genre").select2({
            data: genre
          });
      });

var genre = ['Action', 'Adventure', 'Fantasy', 'Anime', 'Romance'];
    $(document).ready(function() {
    
     $(".genre").select2({
        data: genre
      });
  });
  
  var row ="<td class='nr'><input type='text' placeholder='' size='9'><button id='btn' class='group' style='float:right;'>+</button></td><td><select class='genre' style='width:150px;'></select></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='10' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td>";  


const $groupRow = $("<tr>", {
  class: "group-row"
}).append(row);

const tableBody = $("#movies tbody");
tableBody.on('click', '.group', (e) => {
  tableBody.append($groupRow.clone());
  
      $(".genre").select2({
        data: genre
      });
});
   <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
   </head>
   <h3> Movies </h3>
    <table class="my_table" id="movies" border="1px" style="border-collapse: collapse;">
    <thead>
      <tr><b>
        <td>Group</td>
        <td>Genre</td>
        <td>Movie Name</td>
        <td>Imdb</td>
        <td>Rotten Tomato</td>
        <td>Lead Actress</td>
        <td>Lead Actor</td>
        <td>Year of Release</td>
        <td>Revenue</td>
        <td>Budget</td>
      </tr></b>
    </thead>

    <tbody>
    <tr class="group-row">
    <td class="nr"><input type="text" placeholder="" size="9"><button id="btn" class="group" style="float:right;">+</button>
    </td>
    <td><select class='genre' style="width:150px;"></select></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="10" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    </tr>
    </tbody>
  </table>
...