【问题标题】:Selectize.js: Populate with default valuesSelectize.js:使用默认值填充
【发布时间】:2019-01-19 00:22:57
【问题描述】:

我有一个模态,以 ajax 请求打开以获取要填充的内容,Selectize 就是其中之一。

Ajax 获取一个对象数组来填充 Selectize

let optionsToPopulate = [{id: 6, name: "Foo"},{id: 1, name: "Bar"}]

我将上面的数组传递为:

$("#selectize").selectize({
  options: optionsToPopulate,
  items: optionsToPopulate,
  valueField: 'name',
  labelField: 'name',
  searchField: ['name'],
  plugins: ['remove_button'],
  persist: false,
  createOnBlur: true,
  maxItems: 10,
  create: true
});

但它不起作用,我错过了什么?

【问题讨论】:

    标签: javascript jquery html select selectize.js


    【解决方案1】:

    您需要使用仅包含您希望默认选择的选项值的数组填充items(而不是带有 id、名称等的整个选项对象)。选项“值”由您设置的valueField 确定。例如(因为您的valueField 设置为name):

    items: ["Foo", "Bar"]
    

    请参阅下面的工作 sn-p:

    const options = [{ id: 1, name: "Foo" }, { id: 2, name: "Bar" }];
    const items = options.map(x => x.name);
    $('#select1').selectize({
      options: options,
      items: items,
      valueField: 'name',
      labelField: 'name',
      searchField: ['name'],
      plugins: ['remove_button'],
      persist: false,
      createOnBlur: true,
      maxItems: 10,
      create: true
    });
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Selectize</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.default.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.js"></script>
      </head>
      <body>
        <input id="select1" name="select1" type="text" />
      </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2020-05-26
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      相关资源
      最近更新 更多