How to set a value for a selectize.js input?

后端 未结 11 2116
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 23:51

I have a form from which I would like to copy some default values into the inputs. The form inputs are using the selectize.js plugin. I would like to set some of the form

11条回答
  •  情书的邮戳
    2020-12-14 00:17

    Here is my full code using tag from remote search. Hope this is helpful.

    $('#myInput').selectize({
    valueField: 'id',
    labelField: 'name',
    searchField: 'name',
    options: [],
    delimiter: ',',
    persist: false,
    create: false,
    load: function(query, callback) {
        if (!query.length) return callback();
        $.ajax({
            url: '/api/all_cities.php',
            type: 'GET',
            dataType: 'json',
            data: {
                name: query,
            },
            error: function() {
                callback();
            },
            success: function(res) {
                callback(res);
            }
        });
    },
    onInitialize: function(){
        var selectize = this;
        $.get("/api/selected_cities.php", function( data ) {
            selectize.addOption(data); // This is will add to option
            var selected_items = [];
            $.each(data, function( i, obj) {
                selected_items.push(obj.id);
            });
            selectize.setValue(selected_items); //this will set option values as default
        });
    }
    });
    

提交回复
热议问题