简体   繁体   English

动态添加 select2 下拉菜单不起作用

[英]Dynamically adding select2 dropdown are not working

I have a small requirement, where i need to make a form repeater that contains one of the fields as a select dropdown.我有一个小要求,我需要制作一个表单转发器,其中包含一个字段作为 select 下拉列表。 I have create a jsfiddle to reproduce the issue.我创建了一个 jsfiddle 来重现该问题。

https://jsfiddle.net/varun9522/gwb3rLp9/9/ https://jsfiddle.net/varun9522/gwb3rLp9/9/

[Js Fiddle link with sample code and issue reproduced][1] [Js Fiddle 链接与示例代码和问题转载][1]

The issue on clicking on Add More button, template gets added, but from dropdown I am not able to select or search for an option.单击“添加更多”按钮时出现问题,添加了模板,但从下拉列表中我无法 select 或搜索选项。 Follwing is my HTML:以下是我的 HTML:

<div id="form-repeater">
<div class="row">
  <select class="js-select2">
  </select>
  <button type="button" class="btn btn-primary" 
          id="add-more">Add More</button>
  </div>  
</div>




<div id="template" style='display: none;'>
  <div class="parent-div">
    <div class="row">
      <select class="js-select2">
      </select>

      <button type="button" class="btn btn-primary" 
              id="remove">Remove</button>
    </div>
  </div>
</div>

Following is my javascript:以下是我的 javascript:

$(".js-select2").select2({
  ajax: {
    url: "https://run.mocky.io/v3/651b234e-e668-4143-8c41-2e6a5bafcd27",
    delay: 250,
    processResults: processData
  },
  data: processData([{ "Id": "4", "Code": "JKL", "Description": "Juliet Kilo Laugh" }]).results,
  minimumInputLength: 1,
  escapeMarkup: function (m) { return m; } ,
  templateSelection: myCustomTemplate
});

function processData(data) {
  var mapdata = $.map(data, function (obj) {      
    obj.id = obj.Id;
    obj.text = '[' + obj.Code + '] ' + obj.Description;
    return obj;
  });
  return { results: mapdata }; 
}

function myCustomTemplate(item) {
     return '<strong>' + item.Code + '</strong> - ' + item.Description;
}

$("#add-more").click(function() {
    var content = $('#template').html();
  $('#form-repeater').append(content);
})

$(".remove").click(function(obj) {
    $(obj).closest('.parent-div').remove();
})
$(document).on('click', '.CourseAddButton', function() {
        var configParamsObj = {
                placeholder: 'Select an option...', // Place holder text to place in the select
                minimumResultsForSearch: 3 // Overrides default of 15 set above
                };

        var $thisTable = $(this).closest('table').find('tbody');
        var copyRow = $thisTable.find('tr:first');
        var hasSelect2 = $thisTable.find('.courseNameID').length;
        if (hasSelect2 !== 0) $thisTable.find(".courseNameID").select2('destroy');
        $thisTable.prepend(`<tr>${copyRow.html()}</tr>`);
        if (hasSelect2 !== 0) {
            $thisTable.find('.courseNameID').select2().next().next().remove();
            $thisTable.find('select.courseNameID').select2(configParamsObj);
        }
    });

When You execute $(".js-select2").select2({...});当你执行$(".js-select2").select2({...}); , this selector initialize all select2 linked to this selector , so you initialize too your template. ,这个选择器初始化所有链接到这个选择器的select2 ,所以你也初始化你的模板。

so you have to copy the template and after you initialize the new select2 created.因此您必须复制模板并在初始化创建的新 select2 之后。

so to avoid this problem, i have added first() to the selector所以为了避免这个问题,我在选择器中添加了first()

i have deleted the id of button remove and replaced by class.我已删除按钮删除的 id 并替换为 class。

Another error, when you create button dynamically, if you want to trap event, you have to use the delegation, so i have modifed the event click to destroy the select2 item.另一个错误,当您动态创建按钮时,如果要捕获事件,则必须使用委托,因此我修改了事件单击以销毁 select2 项。

 $("select.js-select2").first().select2({ ajax: { url: "https://run.mocky.io/v3/651b234e-e668-4143-8c41-2e6a5bafcd27", delay: 250, processResults: processData }, data: processData([{ "Id": "4", "Code": "JKL", "Description": "Juliet Kilo Laugh" }]).results, minimumInputLength: 1, escapeMarkup: function(m) { return m; }, templateSelection: myCustomTemplate }); function processData(data) { var mapdata = $.map(data, function(obj) { obj.id = obj.Id; obj.text = '[' + obj.Code + '] ' + obj.Description; return obj; }); return { results: mapdata }; } function myCustomTemplate(item) { return '<strong>' + item.Code + '</strong> - ' + item.Description; } $("#add-more").click(function() { var content = $('#template').html(); $('#form-repeater').append(content); //console.log($("#form-repeater select.js-select2").length) $("#form-repeater select.js-select2").last().select2({ ajax: { url: "https://run.mocky.io/v3/651b234e-e668-4143-8c41-2e6a5bafcd27", delay: 250, processResults: processData }, data: processData([{ "Id": "4", "Code": "JKL", "Description": "Juliet Kilo Laugh" }]).results, minimumInputLength: 1, escapeMarkup: function(m) { return m; }, templateSelection: myCustomTemplate }); }) $("body").on("click", "button.remove", function() { $(this).closest('div.parent-div').remove(); })
 .js-select2 { width: 300px; }
 <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script> <div id="form-repeater"> <div class="row"> <select class="js-select2"> </select> <button type="button" class="btn btn-primary" id="add-more">Add More</button> </div> </div> <div id="template" style='display: none;'> <div class="parent-div"> <div class="row"> <select class="js-select2"> </select> <button type="button" class="btn btn-primary remove">Remove</button> </div> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM