Nicekiwi
Nicekiwi

Reputation: 4807

Selectize.js get more data in "onItemAdd" callback

TL;DR

To make it clearer, I want to have access to ALL the data in the selected JSON object inside the onItemAdd function. Right now I only have access to _id and name via the config variables.


Ok, so I have a working Selectize.js function grabbing a JSON object from my server and creating the select options.

What I want to know is, can I get anymore data from the existing JSON object inside the "onItemSelect" callback?

The only data I can get directly is the value as specified in the config, which in this case is the "_id" and the $item which i assume is form the labelField in the config, in this case is the name form the JSON data.

How can I get more data than that for the selected item? You see in the render object I use the variable item.sku, how can I access the sku variable in the "onItemAdd" callback?

the data form the server is a json array:

[
  { _id: 'abcd1234', name: 'Sample', sku: '00123' }, 
  { _id: 'efgh5678', name: 'Sample2', sku: '00124' }
]

My function

// setup select box to add new products to list
$('#buyingGroupAddProducts').selectize({
  valueField: '_id',
  labelField: 'name',
  searchField: 'name',
  options: [],
  create: false,
  closeAfterSelect: true,
  render: {
    option: function(item, escape) {
      return '<div>'+ escape(item.sku) + ': ' + escape(item.name) + '</div>';
    }
  },
  load: function(query, callback) {
    if (!query.length) return callback();
    $.ajax({
      url: '/buying/products-search',
      type: 'GET',
      dataType: 'json',
      data: {
        q: query
      },
      error: function() {
        callback();
      },
      success: function(res) {
        callback(res);
      }
    });
  },
  onItemAdd: function(value, $item) {

    // DO the thing
    console.log($item);

  }
});

SelectizeJS site: http://selectize.github.io/selectize.js/

Upvotes: 2

Views: 1801

Answers (1)

Moussa
Moussa

Reputation: 4154

a hack to solve your problem : inside onItemAdd function you can access all your JSON : this.options gives you all the selectize options, so now you have the value and the complete JSON, you can easily find back the item in your json that corresponds to the value selected. I can complete my answer if you provide a use case in plunker.

Upvotes: 1

Related Questions