【问题标题】:Select2.js v4.0: how set the default selected value with a local array data source?Select2.js v4.0:如何使用本地数组数据源设置默认选择值?
【发布时间】:2015-10-17 16:53:48
【问题描述】:

使用select2.jsv4插件,当我使用本地数组数据作为源时,如何设置默认选择值?

例如使用此代码

var data_names = [{
  id: 0,
  text: "Henri",
}, {
  id: 1,
  text: "John",
}, {
  id: 2,
  text: "Victor",
}, {
  id: 3,
  text: "Marie",
}];

$('select').select2({
  data: data_names,
});

如何设置id 3为默认选择值?

【问题讨论】:

  • $("#id").select2().select2("val", 'oneofthevaluehere');
  • 从 v4.1 开始,只需执行 {id: 3, text: "Marie", selected: true}。

标签: javascript jquery jquery-select2 jquery-select2-4


【解决方案1】:
$('.select').select2({
        data: data_names,
    }).select2("val",3);

【讨论】:

    【解决方案2】:

    这对我来说适用于 V4.0.3

    $('.select').select2({
        data: data_names,
    })
    $('select').val(3);
    $('select').trigger('change.select2');
    

    【讨论】:

    • 这是 v4 的正确答案。更简洁的你可以写$('.select').val(3).trigger('change')。使用trigger('change.select2') 仅将更改通知 Select2。见select2.github.io/…
    【解决方案3】:

    最好发送另一个属性(在我下面的例子中选择)并使用它来设置默认值。我做了类似下面的事情-

    var data_names = [{
      id: 0,
      text: "Henri",
    }, {
      id: 1,
      text: "John",
    }, {
      id: 2,
      text: "Victor",
    }, {
      id: 3,
      text: "Marie",
      selected: true
    }];
    

    然后做

                $(".select").select2({
                    data : data_names
                });
                data_names.forEach(function(name){
                    if(name.selected) { 
                       $(".select").select2('val',name.id);
                    }
                });
    

    【讨论】:

    • 这是 4.1 版的正确答案。您只需要在数据元素上“选择:true”,不应触发任何事件或调用 API 方法。
    【解决方案4】:

    这对我有用。

    $('#select').select2({data: data_names}).val(3).trigger('change')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-21
      • 2015-10-10
      • 2023-03-08
      • 2018-08-09
      • 2023-02-09
      • 2018-08-06
      • 2015-10-08
      • 2021-11-04
      相关资源
      最近更新 更多