在Jquery转发器内部使用Select2不起作用

问题描述 投票:0回答:3

我使用Select2 Bootstrap https://select2.github.io/通过Ajax远程数据获取和所有这一切在Jquery Repeater中http://briandetering.net/repeater

<div data-repeater-item class="mt-repeater-item">
                                <!-- jQuery Repeater Container -->
<div class="mt-repeater-input">
 <label class="control-label">First Team</label>
  <br/>
 <select name="equipe_1" id="select2-button-addons-single-input-group-sm" class="form-control js-data-example-ajax">
</select>
 </div>
 <div class="mt-repeater-input">
 <label class="control-label">Second Team</label>
<br/>
<select name="equipe_2" id="select2-button-addons-single-input-group-sm" class="form-control js-data-example-ajax">
</select>
</div>
                                <div class="mt-repeater-input">
                                    <a href="javascript:;" data-repeater-delete class="btn btn-danger mt-repeater-delete">
                                        <i class="fa fa-close"></i> Delete</a>
                                </div>
                            </div>

这是我的HTML,但当我点击添加按钮时,我有克隆的表单,但slect2 dropdonw无效。

我的功能Select2 JS文件

$(".js-data-example-ajax").select2({
            placeholder: "Choose a Team...",
            width: "off",
            allowClear: true,
            multiple:false,
            ajax: {
                url: "http://test.dev/teamsearch",
                dataType: 'json',
                type: "POST",
                delay: 2000,
                data: function(params) {
                    return {
                        q: params.term, // search term
                        page: params.page,
                        _token: CSRF_TOKEN
                    };
                },
                processResults: function(data, page) {
                    // 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
                    return {
                        results: data
                    };
                },
                cache: true
            },
            escapeMarkup: function(markup) {
                return markup;
            }, // let our custom formatter work
            minimumInputLength: 4,
            maximumSelectionLength: 1,
            templateResult: formatRepo,
            templateSelection: formatRepoSelection
        });

我的Jquery Repeater文件:

var FormRepeater = function () {

    return {
        //main function to initiate the module
        init: function () {
            
             $('.mt-repeater').each(function(){
        		$(this).repeater({
        			show: function () {

                        $(this).slideDown();


		            },

		            hide: function (deleteElement) {
		                if(confirm('Are you sure you want to delete this element?')) {
		                    $(this).slideUp(deleteElement);
		                }
		            },

		            ready: function (setIndexes) {

		            }

        		});
        	});
        }

    };

}();

jQuery(document).ready(function() {
    FormRepeater.init();

});

我使用Select2 ajax加载团队内部列表。

当jquery repeater克隆我的表单时,如何使select2工作?谢谢

jquery ajax repeater laravel-5.3 select2
3个回答
0
投票

看看jQuery form repeater and select2 dont work together。基本问题是您需要在转发器创建后在每个新选择框上调用.select2()


0
投票

不知道这个答案是否来得太晚,或者根本不需要它,但我认为它可能在将来帮助某人。

所以我有一段时间遇到这个问题,我通过做Bindrid所说的解决了它,并在用户在表单转发器上执行的每个Add操作中调用.select2()。我正在使用C#MVC 5,jquery-repeater v1.2.1和select2 v4.0.3。

随意帮助改进此代码。

我的ViewModel:

public class MedicalCareViewModel
{
   [Display(Name = "ICD")]
   [Require(ErrorMessage = "This field is required")]
   public List<RelatedICDViewModel> RelatedICD { get; set; }
}

public class RelatedICDViewModel
{
   public int Code { get; set; }

   public string AbbreviatedDescription { get; set; }
}

我的控制器:

public ViewResult MedicalCare(int id)
{
   var medicalCare = MedicalCareService.GetById(id);
   var model = Mapper.Map<MedicalCareViewModel>(medicalCare);

   // This is for pre-loaded data, if you don't have to show pre-loaded data skip this
   // Here's the catch, you'll have to iterate through your selected values in the 
   // select box and for each element you'll have to create a list of 
   // selected items with just the item selected so you can then 
   // iterate in the view and 'show' the form-repeater it's values.
   // Since each select list item have the Selected propertie set to true
   // select2 will know what to do
   foreach(var ICD in model.RelatedICD)
      ViewData[$"Index[{model.RelatedICD.IndexOf(ICD)}]"] = new List<SelectlistItem> 
   {
      new SelectListItem
      {
         Value = ICD.Code.ToString(),
         Text = ICD.AbbreviatedDescription,
         Selected = true
      }
   };

   return View(model);
}

我的看法:

@model MedicalCareViewModel
@using(Html.BeginForm("MedicalCare", "MedicalHistory", new {area = "Medical"}, FormMethod.Post, new { enctype = "multipart/form-data"} ))
{
   // other form fields
   // Initialize the repeater by setting an ID to a div
   <div id="rpRelatedICD">
      <div data-repeater-list="RelatedICD">
         // This conditional is for pre-loaded data, if you don't need to 
         // show pre-loaded data just use the else part
         @if(Model.RelatedICD.Any())
         {
            for(var i = 0; i < Model.RelatedICD.Count; i++)
            {
            <div data-repeater-item>
               // It's important to define a class to the select box so 
               // you can on every add action on the repeater call the 
               // select2 initializer
               @Html.DropDownListFor(model => model.RelatedICD, ViewData[$"Index[{i}]"] as List<SelectListItem>, new {@class = "RelatedICD"})
               <input data-repeater-delete type="button" value="Remove" class="ui-button ui-corner-all ui-widget" role="button">
            </div>
            }
         }
         else
         {
            <div data-repeater-item>
               // It's important to define a class to the select box so 
               // you can on every add action on the repeater call the 
               // select2 initializer
               @Html.DropDownListFor(model => model.RelatedICD, new List<SelectListItem>(), new {@class = "RelatedICD"})
               <input data-repeater-delete type="button" value="Remove" class="ui-button ui-corner-all ui-widget" role="button">
            </div>
         }
         <div>
                <input data-repeater-create="" type="button" value="Add" class="ui-button ui-corner-all ui-widget" role="button">
         </div>
      </div>
   </div>
}

我的JS:

<script type="text/javascript">
   $(document).ready(function() {
      initializeICDRepeater();
      initializeICDSelect2();
   });

   function initializeICDRepeater() {
      $("#rpRelatedICD").repeater({
         initEmpty: false,
         show: function() {
            $(this).slideDown();
            // like Bindrid said, on every Add action call the select2 initializer
            initializeICDSelect2(); 
         },
         hide: function(deleteElement) {
            $(this).slideUp(deleteElement);
         }
      });
   }

   function initializeICDSelect2() {
       $(".RelatedICD").select2({
       ajax: { /* your ajax definition */ },
       allowClear: true // || false it's your choice
       });
   }
</script>

0
投票

这是一个在表格中继器按钮时钟初始化select2的解决方案。

在初始化select2之前,它只等待一小段时间,确保在初始化select2时项目已经重复。

<script type="text/javascript">
    $("#clone-button").click(function(){
        setTimeout(function(){
            $(".select2").select2({
                placeholder: "Select a state",
                allowClear: true
            }); 
        }, 100);
    }); 
</script>

有关问题和解决方案see here的深入概述

© www.soinside.com 2019 - 2024. All rights reserved.