How to clone select2 v4 Ajax

£可爱£侵袭症+ 提交于 2020-01-14 03:11:28

问题


I am attempting to do an AJAX call with the Select2 ver4 jquery plugin and Using Loading remote data of Select2 sample page I am trying to clone a select which contains select2 tool. But select2 dropdown disabled when cloning.

HTML CODE

<tr>
<td>
<select class="js-example-data-ajax" id="sel1">
</select>
<button type="button" class="addline">Add Line</button>
</td>
</tr>

jQuery CODE

     $.fn.select2.amd.require(
    ["select2/core", "select2/utils", "select2/compat/matcher"],
    function (Select2, Utils, oldMatcher) {

  var $ajax = $(".js-example-data-ajax");

  function formatRepo (repo) {
    if (repo.loading) return repo.text;

    var markup = '<div class="clearfix">' +
    '<div class="col-sm-1">' +
    '<img src="' + repo.owner.avatar_url + '" style="max-width: 100%" />' +
    '</div>' +
    '<div clas="col-sm-10">' +
    '<div class="clearfix">' +
    '<div class="col-sm-6">' + repo.full_name + '</div>' +
    '<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
    '<div class="col-sm-2"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
    '</div>';

    if (repo.description) {
      markup += '<div>' + repo.description + '</div>';
    }

    markup += '</div></div>';

    return markup;
  }

  function formatRepoSelection (repo) {
    return repo.full_name || repo.text;
  }

  $ajax.select2({
    ajax: {
      url: "https://api.github.com/search/repositories",
      dataType: 'json',
      delay: 250,
      data: function (params) {
        return {
          q: params.term // search term
        };
      },
      processResults: function (data, params) {
        // parse the results into the format expected by Select2
        // since we are using custom formatting functions we do not need to
        // alter the remote JSON data, except to indicate that infinite
        // scrolling can be used
        params.page = params.page || 1;

        return {
          results: data
        };
      },
      cache: true
    },
    escapeMarkup: function (markup) { return markup; },
    minimumInputLength: 1,
  });
});

$(document).on('click', '.addline', function () {
    var $tr = $(this).closest('tr');
    var $lastTr = $tr.closest('table').find('tr:last');

    $lastTr.find('.js-example-data-ajax').select2('destroy');

    var $clone = $lastTr.clone();

    $clone.find('td').each(function() {
        var el = $(this).find(':first-child');
        var id = el.attr('id') || null;
        if (id) {
            var i = id.substr(id.length - 1);
            var prefix = id.substr(0, (id.length - 1));
            el.attr('id', prefix + (+i + 1));
            el.attr('name', prefix + (+i + 1));
        }
    });
    $tr.closest('tbody').append($clone);
    $lastTr.find('.js-example-data-ajax').select2();
    $clone.find('.js-example-data-ajax').select2();
});
$('.js-example-data-ajax').select2();

回答1:


After creating the clone, you have to run the very same select2 arguments for it (in addition to your original one that you've destroyed). You can either declare the arguments as a global variable and then use it in the two places (which is better practice), or to include them again, which for the sake of optimized answer you can see below:

$(document).on('click', '.addline', function () {
    var $tr = $(this).closest('tr');
    var $lastTr = $tr.closest('table').find('tr:last');

    $lastTr.find('.js-example-data-ajax').select2('destroy');

    var $clone = $lastTr.clone();

    $clone.find('td').each(function() {
        var el = $(this).find(':first-child');
        var id = el.attr('id') || null;
        if (id) {
            var i = id.substr(id.length - 1);
            var prefix = id.substr(0, (id.length - 1));
            el.attr('id', prefix + (+i + 1));
            el.attr('name', prefix + (+i + 1));
        }
    });
    $tr.closest('tbody').append($clone);

    // ADDED:
    $(".js-example-data-ajax").select2({
      ajax: {
        url: "https://api.github.com/search/repositories",
        dataType: 'json',
        delay: 250,
        data: function (params) {
          return {
            q: params.term // search term
          };
        },
        processResults: function (data, params) {
          // parse the results into the format expected by Select2
          // since we are using custom formatting functions we do not need to
          // alter the remote JSON data, except to indicate that infinite
          // scrolling can be used
          params.page = params.page || 1;

          return {
            results: data
          };
        },
        cache: true
      },
      escapeMarkup: function (markup) { return markup; },
      minimumInputLength: 1,
    });

    // BAD PRACTICE: Make the entire { ajax: ...} block as a global variable,
    // then use it both here and on your original $ajax.select2(...) call.

});


来源:https://stackoverflow.com/questions/32415132/how-to-clone-select2-v4-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!