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

时间:2017-01-15 22:05:26

标签: jquery ajax repeater laravel-5.3 select2

我正在使用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工作? 感谢的

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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>

答案 2 :(得分: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

的深入概述