Selectize: Setting Default Value in onInitialize with setValue
Asked Answered
T

5

6

I have a web application with multiple Selectize objects initialized on the page. I'm trying to have each instance load a default value based on the query string when the page loads, where ?<obj.name>=<KeywordID>. All URL parameters have already been serialized are are a dictionary call that.urlParams.

I know there are other ways to initializing Selectize with a default value I could try; but, I'm curious why calling setValue inside onInitialize isn't working for me because I'm getting any error messages when I run this code.

I'm bundling all this JavaScript with Browserify, but I don't think that's contributing to this problem.

In terms of debugging, I've tried logging this to the console inside onInititalize and found that setValue is up one level in the Function.prototype property, the options property is full of data from load, the key for those objects inside options corresponds to the KeywordID. But when I log getValue(val) to the console, I get an empty string. Is there a way to make this work or am I ignoring something about Selectize or JavaScript?

module.exports = function() {    
    var that = this;

    ...

    this.selectize = $(this).container.selectize({
        valueField: 'KeywordID',  // an integer value
        create: false,
        labelField: 'Name',
        searchField: 'Name',
        preload: true,
        allowEmptyOptions: true,
        closeAfterSelect: true,
        maxItems: 1,
        render: {
           option: function(item) {
                return that.template(item);
            },
        },
        onInitialize: function() {
            var val = parseInt(that.urlParams[that.name], 10);  // e.g. 5
            this.setValue(val);
        },
        load: function(query, callback) {
            $.ajax({
                url: that.url,
                type: 'GET',
                error: callback,
                success: callback
            })
        }
    });

};

...
Tabernacle answered 14/6, 2016 at 18:51 Comment(2)
have you tried using the options property? github.com/selectize/selectize.js/blob/master/docs/usage.mdCheapen
When the page loads, I only know the valueField via url parameter, so I need load to fetch the data from the API before I can map the valueField to its option object, then select it that option default value via setValue. I think the problem with the above code is that onInitialize fires before load does, even if preload: true. I might try having the data already bootstrapped into the page when it loads, and see if onInitialize behaves the way I want.Tabernacle
T
3

After sprinkling in some console.logs into Selectize.js, I found that the ajax data hadn't been imported, when the initialize event was triggered. I ended up finding a solution using jQuery.when() to make setValue fire after the data had been loaded, but I still wish I could find a one-function-does-one-thing solution.

module.exports = function() {    
    var that = this;

    ...

    this.selectize = $(this).container.selectize({
        valueField: 'KeywordID',  // an integer value
        create: false,
        labelField: 'Name',
        searchField: 'Name',
        preload: true,
        allowEmptyOptions: true,
        closeAfterSelect: true,
        maxItems: 1,
        render: {
           option: function(item) {
                return that.template(item);
            },
        },
        load: function(query, callback) {
            var self = this;
            $.when( $.ajax({
                url: that.url,
                type: 'GET',
                error: callback,
                success: callback
            }) ).then(function() {
                var val = parseInt(that.urlParams[that.name], 10);  // e.g. 5
                self.setValue(val);
            });
        }
    });

};

...
Tabernacle answered 14/6, 2016 at 23:25 Comment(0)
R
2

You just need to add the option before setting it as the value, as this line in addItem will be checking for it: if (!self.options.hasOwnProperty(value)) return;

inside onInitialize you would do:

var val = that.urlParams[that.name]; //It might work with parseInt, I haven't used integers in selectize options though, only strings.
var opt = {id:val, text:val};
self.addOption(opt);
self.setValue(opt.id);
Roper answered 14/6, 2016 at 23:40 Comment(0)
P
2

Instead of using onInitialize you could add a load trigger to the selectize. This will fire after the load has finished and will execute setValue() as expected.

var $select = $(this).container.selectize({
    // ...
    load: function(query, callback) {
        // ...
    }
});
var selectize = $select[0].selectize;
selectize.on('load', function(options) {
    // ...
    selectize.setValue(val);
});

Note that for this you first have to get the selectize instanze ($select[0].selectize).

Politicize answered 22/3, 2020 at 14:6 Comment(0)
A
0

in my case it need refresh i just added another command beside it

                $select[0].selectize.setValue(opt);

i added this $select[0].selectize.options[opt].selected = true;

and changes applied

but i dont know why?

Attested answered 5/8, 2020 at 19:58 Comment(0)
E
0

You can initialize each selectize' selected value by setting the items property. Fetch the value from your querystring then add it as an item of the items property value:

const selectedValue = getQueryStringValue('name') //set your query string value here

$('#sel').selectize({
    valueField: 'id',
    labelField: 'title',
    preload: true,
    options: [
        { id: 0, title: 'Item 1' },
        { id: 1, title: 'Item 2' },
    ],
    items: [ selectedValue ],
});

Since it accepts array, you can set multiple selected items

Emulsoid answered 29/8, 2022 at 1:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.