Gammer
Gammer

Reputation: 5628

Selectize.js: Populate with default values

I have a modal, opens with an ajax request to get stuff to populate, Selectize is one them.

Ajax gets an array of objects to populate the Selectize :

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

And i am passing the above array as :

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

But its not working, What am i missing ?

Upvotes: 2

Views: 2741

Answers (1)

benvc
benvc

Reputation: 15130

You need to populate items with an array of just the values of the options that you want to be selected by default (not the entire option object with id, name, etc). The option "value" is determined by the valueField you set. For example (since your valueField is set to name):

items: ["Foo", "Bar"]

See working snippet below:

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>

Upvotes: 2

Related Questions