jQuery Select2问题显示选择

时间:2016-12-09 18:24:36

标签: javascript jquery jquery-select2 select2

我正在选择菜单,我使用Select-2插件来自定义它。因此,我有一个问题,我尝试在输入字段中重新创建所选项目。因此,当您选择项目时,它在输入字段中显示为小灰名单项。

这是一个 FIDDLE ,它显示了我遇到的问题。

这是javascript代码我如何呈现我的输入字段:

var selectMenuItems = [
        {id: 'restaurant', value: 'restaurant'},
        {id: 'shopping', value: 'shopping'},
        {id: 'toilet', value: 'toilet'}
    ]

     function formatSelectItem (selectItem) {
        if (!selectItem.id) { return selectItem.value; }
        var $selectItem = $(
        '<img src="img/markers/'+ selectItem.id.toLowerCase() +'.png"/>' +
        '<span class="select-item-text">'+ selectItem.value+"</span>"
        );
        return $selectItem;
    };

    $("[name='select']").select2({
        placeholder: "Selecteer een categorie",
        templateResult: formatSelectItem,
        data: selectMenuItems
    }).on("change", function(e){
        console.log(e);

        $('.select-multiple :selected').each(function(i, selected) {
            var selectedValue = $(selected).val();

            $('.select2-selection__choice').text(selectedValue);
        });
    });

问题在于,当我选择一个项目时,它会在输入字段中显示文本,但如果我选择多个项目,则所有项目都将更改为最后选择的项目文本。我怎样才能将此.text()绑定到该特定的选择项?

在插件Select-2 plugin的文档中,有一个名为&#34; Templating&#34;的示例。他们不必将文本或图像附加到所选项目..

4 个答案:

答案 0 :(得分:2)

<强> Working fiddle

您要查找的是每次循环$(this).val()提供的选择值,并使用.select2-selection__choice将值附加到.eq()索引:

$("[name='select']").select2({
  placeholder: "Selecteer een categorie",
  templateResult: formatSelectItem,
  data: selectMenuItems
}).on("change", function(e){
  $.each($(this).val(), function(i, selected) {
    $('.select2-selection__choice').eq(i).prepend(selected+' ');
  });
});

注意:使用prepend()代替tex()来保留代码中的“X”。

希望这有帮助。

(function($) {
  $(function() {
    var selectMenuItems = [
      {id: 'restaurant', value: 'restaurant'},
      {id: 'shopping', value: 'shopping'},
      {id: 'toilet', value: 'toilet'}
    ]

    function formatSelectItem (selectItem) {
      if (!selectItem.id) { return selectItem.value; }
      var $selectItem = $(
        '<img src="img/markers/'+ selectItem.id.toLowerCase() +'.png"/>' +
        '<span class="select-item-text">'+ selectItem.value+"</span>"
      );
      return $selectItem;
    };

    $("[name='select']").select2({
      placeholder: "Selecteer een categorie",
      templateResult: formatSelectItem,
      data: selectMenuItems
    }).on("change", function(e){
      $.each($(this).val(), function(i, selected) {
        $('.select2-selection__choice').eq(i).prepend(selected+' ');
      });
    });

  });
})(jQuery);            
.flag-text { margin-left: 10px; }

.select2 {
  width: 100% !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<select id="type" name="select" class="select-multiple" multiple="multiple" data-role="none"></select>

使用图片的小部件:

(function($) {
  $(function() {
    var selectMenuItems = [
      {id: 'restaurant', value: 'restaurant', img: 'https://www.hughesinsurance.co.uk/img/front/map-marker.png'},
      {id: 'shopping', value: 'shopping', img: 'http://king-of-truck.byclickeat.fr/media/cache/square_40/front/bundle/clickeat/img/map-marker.png'},
      {id: 'toilet', value: 'toilet', img: 'http://www.onebabyowner.co.uk/sites/all/themes/onebabyowner/img/icon/map-marker.png'}
    ]

    function formatSelectItem (selectItem) {
      if (!selectItem.id) { return selectItem.value; }
      var $selectItem = $(
        '<img src="'+ selectItem.img +'"/>' +
        '<span class="select-item-text">'+ selectItem.value+"</span>"
      );
      return $selectItem;
    };

    $("[name='select']").select2({
      placeholder: "Selecteer een categorie",
      templateResult: formatSelectItem,
      data: selectMenuItems
    }).on("change", function(e){
      $.each($(this).val(), function(i, selected) {
        $('.select2-selection__choice').eq(i).prepend(selected+' ');
      });
    });

  });
})(jQuery);            
.flag-text { margin-left: 10px; }

.select2 {
  width: 100% !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<select id="type" name="select" class="select-multiple" multiple="multiple" data-role="none"></select>

答案 1 :(得分:1)

这是最简短的方法:

$('.select-multiple :selected').each(function(i, selected) {
   $('.select2-selection__choice').eq(i).text($(this).val());
});

如果要在所选的选项中包含图像,请使用templateSelection功能。您可以通过将templateSelection选项设置为JavaScript函数来覆盖选择的显示。

(function($) {
        $(function() {
            var selectMenuItems = [
               {id: 'restaurant', text: 'restaurant', img: 'http://www.freeiconspng.com/uploads/restaurant-icon-png-7.png'},
               {id: 'shopping', text: 'shopping', img: 'http://www.pngall.com/wp-content/uploads/2016/04/Shopping-Free-PNG-Image.png'},
               {id: 'toilet', text: 'toilet', img: 'http://www.freeiconspng.com/uploads/toilet-icon-png-32.png'}
            ]

            function formatSelectItem (selectItem) {
                if (!selectItem.id) { return selectItem.text; }
                var $selectItem = $(
                    '<img src="'+ selectItem.img +'" width="50px" height="50px"/>' +
                    '<span class="select-item-text">'+ selectItem.text+"</span>"
                );
               return $selectItem;
            };
            function formatState (opt) {
                if (!opt.id) {
                   return opt.text;
                }                               
                var $opt = $(
                  '<span><img src="'+opt.img +'" width="50px" height="50px"/>' + opt.text + '</span>'
                );
                return $opt;
            };
            $("[name='select']").select2({
               placeholder: "Selecteer een categorie",
               templateResult: formatSelectItem,
               templateSelection: formatState,
               data: selectMenuItems
            });
            
        });
})(jQuery);            
.flag-text { margin-left: 10px; }

.select2 {
  width: 100% !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<select id="type" name="select" class="select-multiple" multiple="multiple" data-role="none"></select>

答案 2 :(得分:0)

在您的代码中

        $('.select-multiple :selected').each(function(i, selected) {
            var selectedValue = $(selected).val();

            $('.select2-selection__choice').text(selectedValue);
        });

您需要将selectedValue拆分为值并搜索每个值以放入适合该值索引的文本。

换句话说,将代码替换为:

     $('.select-multiple :selected').each(function(i, selected) {
        var selectedValue = $(this).val();
        $('.select2-selection__choice').eq(i).text(selectedValue);
      });

答案 3 :(得分:0)

我认为我必须使用jquery执行此操作,但当我将selectMenuItems Array的{​​{1}}更改为value时,插件会为我工作:

text

只是一个简单的修复,我认为我可以在那里设置任何属性