首页 > 解决方案 > Select2 以编程方式更改数据

问题描述

当我更改另一个 select2 下拉列表的值时,我试图以编程方式更改 select2 下拉列表中的数据集。

我遇到的问题很奇怪,因为它似乎改变了徽章值而不是选项本身。您可以在徽章中看到 2 和 3,但一个数据集中的文本值完全不同,但不会更改选项。

这是一个展示我的意思的小提琴。https://jsfiddle.net/jamiebrs/8axy7123/

这是formatText功能:

function formatText (icon) {
  if(icon.badge == undefined){
    return  $('<span>' + icon.text + '</span>');
  } else {
    return  $('<span><span class="badge">'+ icon.badge + '</span> ' + icon.text + '</span>');
  }
}

这是在选择选项时试图触发更改#products下拉选项的事件#fam。该eval(d)调用采用选定的值并检索我定义的相应变量,其中包含#products.

$('#fam').select2().on('change', function() {
  d = $(this).val();

  $('#products').val(null).trigger('change');
  $('#products').select2({
    data: eval(d),
    width: "100%",
    theme: 'bootstrap4',
    placeholder: "Select item",
    allowClear: true,
    templateSelection: formatText,
    templateResult: formatText
  }).trigger('change');
})

标签: jqueryformsjquery-select2

解决方案


你有几个问题需要解决。首先,一旦 select2 用数据初始化,它将保留所有选项。您调用此代码的代码:

$('#products').val(null).trigger('change')

不会从下拉列表中清空选项,它只是取消选择已选择的任何选项(因此,如果您选择了“增强”和“错误”,它将取消选择这些选项)。我假设您查看了select2 文档的Clearing Selections部分并假设它清空了选项。

您需要做的是完全清除所有选项,销毁 select2 实例,然后使用正确的数据重新初始化它,如下所示:

$('#products').empty().select('destroy').select2({/* your options here */});

我在你的问题中注意到并摆弄了一些我建议你改变的事情:

  1. 将您的#products配置移动到一个变量中,以便您可以重用和覆盖它
  2. 将您的#products选项放入由相应#fam选项值作为键的对象中,以便您可以从该对象中检索正确的选项,而不是调用eval()危险且不应该使用的选项。

您的代码将如下所示:

const productOptions = {data1: [/*...*/], data2: [/*...*/]};
const productsConfig = {
  width: "100%",
  theme: 'bootstrap4',
  placeholder: "Select item",
  allowClear: true,
  templateSelection: formatText,
  templateResult: formatText
};

$('#fam').select2().on('change', function() {
  // get selected value from the #fam select2
  const selected = $(this).val();

  // get the new products config (products config + data options)
  const newProductsConfig = Object.assign({},
    productsConfig,
    {data: productOptions[selected]}
  );

  // destroy the existing products select2 and re-initialize
  $('#products').empty().select2('destroy').select2(newProductsConfig);
});

然后,当您最初加载页面时,您可以使用 products 配置对其进行初始化,然后在触发.change()事件的同时初始化 fam select2 以自动填充产品选项:

// initialize the products select2 on page load
$('#products').select2(productsConfig);

// initialize the fam select2 and trigger the change event
// which will properly populate products options with whatever
// fam option is currently selected on page load
$('#fam').select2({
  theme: 'bootstrap4', 
  placeholder: "Select item",
  width: "100%"
}).change();

推荐阅读