【问题标题】:Can't set multiple values in Select2无法在 Select2 中设置多个值
【发布时间】:2014-09-14 08:23:24
【问题描述】:

我正在尝试在 select2-jquery 组件中显示选定的值。

var select = $(".select2").select2({
    multiple: true,
    placeholder: "",
    width:'100%',
    data: z 
});
var selectedValues = $("#sourceValues").val().split(',');

$.each( selectedValues, function(k,v){
    $(".select2").select2('val',v);
})

元素sourceValues 保存值,例如:2,4 z 是包含建议的 id 和 text 的对象数组。 我可以看到链接到 Select2 元素的<options>,但我无法在元素上显示选定的值。 另外,如果我尝试在 Chrome 控制台上运行查询,如果我写类似 ;

  $(".select2").select2('val',4) 

因此,id 为 4 的 <option> 被选中。

【问题讨论】:

  • 有没有试过直接设置数组:$(".select2").select2('val', selectedValues);?
  • 是的,现在可以了,谢谢

标签: javascript jquery jquery-select2


【解决方案1】:

Select2 4.0 版本以备不时之需:

var selectedValues = $("#sourceValues").val().split(',');
$(".select2").val(selectedValues).trigger("change");

【讨论】:

  • 谢谢先生。我已经在谷歌上搜索了一个多小时! :D
  • 我的天啊,我一直在绞尽脑汁尝试所有可能的解决方案,但无济于事,结果成功了,非常感谢!都是关于.val().split(',');
  • 这应该更改为接受的答案,如赞成票所证明的那样。谢谢。
【解决方案2】:

更新(Select2 4.0+)

从 4.0 版开始,您应该使用 .val(...),后跟来自 jQuery 的 trigger('change')

https://select2.org/programmatic-control/add-select-clear-items#selecting-options

最新示例:

var selectedValues = $("#sourceValues").val().split(',');
$(".select2").val(selectedValues).trigger('change');

// $(".select2").val([1, 2]).trigger('change');

原答案(Select2 3.5.3)

http://select2.github.io/select2/#documentation

附加选择 - 多值 - 值属性的数组 应该选择的选项。 null 为空。

所以:

var selectedValues = $("#sourceValues").val().split(',');
$(".select2").select2('val',selectedValues);

// $(".select2").select2('val',[1, 2]);

【讨论】:

  • 这似乎不适用于多选,或者我遗漏了一些东西。
  • 对于 4.0.2 $('.select2').val(selectedValues); 似乎正在工作
【解决方案3】:
var selectedValues = $("#sourceValues").val().split(',');
var $multiSelect = $(".select2").select2();
$multiSelect.val(selectedValues).trigger("change");

【讨论】:

    【解决方案4】:

    例如在循环中创建动态数组,这样做:

     data=[]
    
        for(let input of inputs){
    
              *//key of dynamic build*
               if(typeof data[input.name]==='undefined'){
                    data[input.name]=[]}
                data[input.name].push(input.value);
                console.log(data)
            }
    

    【讨论】:

      【解决方案5】:

      嘿,我发现并稍微升级并使用 ŁukaszW.pl 建议JavaScript/jQuery set values selection in a multiple select,您也可以使用它:

      在 jQuery 中:

      var values = ["Test", "Prof", "Off"]; // or to take values as array from other document element;
      $("#strings").val(values);
      $("#strings").trigger('change'); //trigger change for select2 to set values/styles
      

      或纯 JavaScript:

      var element = document.getElementById('strings');
      var values = ["Test", "Prof", "Off"]; // or to take values as array from other document element;
      for (var i = 0; i < element.options.length; i++) {
          element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
      }
      var event = new Event('change'); 
      var sel = document.getElementById("strings"); 
      sel.dispatchEvent(event); //trigger change for select2 to set values/styles
      

      jQuery 在这里做了重要的抽象。

      并保存:) 希望它可以帮助某人:)

      【讨论】:

        【解决方案6】:

        给定:

        1. select2 v4
        2. “选项”在从数据库中绘制页面时获取一个php脚本

        必须像在数据库中一样填写select2。默认情况下,它呈现如下:选项值描述

        我解决了这样的问题: 从“select2-searchable”类中,我包含 html atrrribute (来自 php)

        $('.select2-searchable').each(function(i, e) { //table, interation all elements
            $(e).select2({
                minimumResultsForSearch: 1,
                width: 'resolve',
            });
            if ($(e).attr('data-reorder')) {
                $(e).on('select2:select', function(el) { //adding a new value to the end of the list
                    $(this).append(el.params.data.element).trigger('change.select2');
                });
                if ($(e).attr('data-value')) { //sorting by values from the database
                    $.each($(e).attr('data-value').split(','), function(j, k) {
                        $(e).find('[value=' + k + ']').each(function(m, l) {
                            l.selected = true;
                            $(e).append(l).trigger('change');
                        });
                    });
                }
            }
        });
        

        此处的示例 (https://jsfiddle.net/M0rdent/q9gn305d/3/)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-02
          • 1970-01-01
          • 1970-01-01
          • 2014-08-12
          • 1970-01-01
          • 2019-01-14
          相关资源
          最近更新 更多