Selectize.js预填充

时间:2018-07-26 18:38:53

标签: javascript jquery html selectize.js

我有以下selectize.js

  $("#abc").selectize({
      valueField: 'name',
      labelField: 'name',
      searchField: ['name'],
      plugins: ['remove_button'],
      createOnBlur: true,
      maxItems: 10,
      preload: true,
      create:function (input){
        callback({ name:'Cricket', name:'Football', name : 'Tennis'})
      },
  });

html代码是:

<select id="abc" name="sport[]"></select>

我希望CricketFootballTennis预先加载,这意味着它应该在页面加载时自动加载。 但是这些选项没有加载,我想念什么?

1 个答案:

答案 0 :(得分:2)

似乎您可能只是在寻找options属性来设置选择选项的初始列表,而在items属性中选择要默认的选项。如果是这样,则不需要create函数(通过该函数可以自定义对用户输入的选项的处理)。见下文。

$('#abc').selectize({
  options: [
    {name: 'Cricket'},
    {name: 'Football'},
    {name: 'Tennis'}
  ],
  items: [
    'Cricket',
    'Football',
    'Tennis'
  ],
  valueField: 'name',
  labelField: 'name',
  searchField: ['name'],
  plugins: ['remove_button'],
  createOnBlur: true,
  maxItems: 10,
  preload: 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>

    <form action="" method="POST">
      <input id="abc" name="abc" type="text" />
      <button type="submit">Submit</button>
    </form>
    
    <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>