Me Unagi
Me Unagi

Reputation: 625

Setting default values with selectize api for listbox in selectize.js

I am trying to set default value upon page load in a dropdown listbox which loads value thru an ajax call. Not able to set values using setValue method as suggested in the docs. Please help. Following are code snippets from the project

HTML

<select name="country" placeholder="Please Select Country  ..."></select>

Data population JS code

  $('[name="country"]').selectize({
    valueField: 'name',
    labelField: 'name',
    searchField: 'name',
    preload: true,
    create: false,
    render: {
      option: function(item, escape) {
        return '<div>' + escape(item['name']) + '</div>';
      }
    },

    load: function(query, callback) {
          $.ajax({
            url: '/countrydata',
            type: 'GET',
            error: function() {
                callback();
            },
        success: function(res) {
            callback(res);
        }
      });
    },
  });

Default Value Setting Code

$('[name="country"]').selectize();
$('[name="country"]')[0].selectize.setValue("Japan");

Is there a hack where I can circumvent the problem ? I am been trying to get this work for couple of days now.

Thank you for reading. Any help would be appreciated.

Upvotes: 2

Views: 1680

Answers (1)

basher
basher

Reputation: 2391

You're close, but I believe your issue is that you're attempting to set the value to an option that doesn't exist in the list. You need to add the option first:

$('[name="country"]').selectize();
var item = {};
item.name = "Japan"; //Based on your render function, which uses item['name'] and labelField, searchField, etc.
$('[name="country"]')[0].selectize.addOption(item);
$('[name="country"]')[0].selectize.setValue(item.name);

Upvotes: 3

Related Questions