Selectize.js: How to prefetch all options from REST API without needing to type anything in the box

Created on 26 Apr 2016  路  2Comments  路  Source: selectize/selectize.js

This is the code I have:

    // Selectize stuff
    function selectize_fields(field, endpoint, json_namespace) {
        var dropdown = $(field).selectize({
            valueField: 'uid',
            labelField: 'name',
            searchField: ['uid', 'name'],
            options: [],
            create: false,
            render: {
                option: function(item, escape) {
                    return '<div>' + item.name + '</div>';
                }
            },
            load: function(query, callback) {
                if (!query.length) return callback();
                $.ajax({
                    url: endpoint,
                    type: 'GET',
                    dataType: 'json',
                    error: function() {
                        console.log('Error loading ' + field);
                        callback();
                    },
                    success: function(res) {
                        console.log('Success loading ' + json_namespace);
                        callback(res.data[json_namespace]);
                    }
                });
            }
        });
    };
    selectize_fields('#selectize-passion', '/api/v1/passions', 'passions');
    selectize_fields('#selectize-current-city', '/api/v1/cities', 'cities')

After the page loads, if I click on the text box no AJAX request is sent. However, on typing something, the request is sent.

Most helpful comment

@jbanety In addition to the preload option, I also had to remove this line : if (!query.length) return callback();. Thanks!

All 2 comments

Hi @kevinisaac,
you can prefetch your items with the preload option set to true.

@jbanety In addition to the preload option, I also had to remove this line : if (!query.length) return callback();. Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jaideepYes picture jaideepYes  路  5Comments

adrianmihalko picture adrianmihalko  路  4Comments

shoaibshakeel381 picture shoaibshakeel381  路  5Comments

stevelacey picture stevelacey  路  4Comments

daveedwards45 picture daveedwards45  路  3Comments