Selectize.js:使用默认值填充

时间:2018-08-11 18:20:41

标签: javascript jquery html select selectize.js

我有一个模式,以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
});

但是它不起作用,我想念什么?

1 个答案:

答案 0 :(得分:0)

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

items: ["Foo", "Bar"]

请参见下面的工作片段:

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">
  </head>

  <body>

    <input id="select1" name="select1" type="text" />

    <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>

  </body>

</html>