How to add item into selectize js automatically after document ready?

 

Questions


I have selectize js code. It runs well and shows right option after i type key on select box.

Here is the code :

$('#select-links').selectize({
        maxItems: diffItems,
        valueField: 'nick_name',
        labelField: 'full_name',
        searchField: ['nick_name', 'full_name'],
        options: [],
        create: false,
        render: {
            item: function(item, escape) {
                return '<div id="' + escape(item.id) + '">' +
                    '<span class="nick_name">' + escape(item.full_name) + '</span>' +
                    '<span class="full_name"> &lt;' + escape(item.nick_name) + '&gt;</span>' +
                '</div>';
            },
            option: function(item, escape) {
                return '<div class="box-user clearfix">' +
                      '<div class="thumb col-xs-1 mr10">' +
                          '<img class="lazyload" src="'+escape(item.avatar)+'" data-src="' + escape(item.avatar)+'">' +
                      '</div>' +
                      '<div class="col-xs-8">' +
                          '<span class="label" style="color: #000;">' + escape(item.full_name) + '</span>' +
                          '<span class="caption">/' + escape(item.nick_name) + '</span>' +
                      '</div>' +
                '</div>';
            }
        },
        load: function(query, callback) {
            if (!query.length) return callback();
            $.ajax({
                url: '/ajax/origin/search',
                type: 'GET',
                dataType: 'json',
                data: {
                    q: query
                },
                error: function() {
                    callback();
                },
                success: function(res) {
                    callback(res);
                }
            });
        }
    });

But, i got the problem.

After document ready, i want selectize add item automatically after document / page has already loaded without i have to type the key on select box. How is the code?

    @if(isset($_POST['nick']))
        $(".chat__list--active").show();
        $(".edit").hide();
        $('.chat__list').hide();
        $('#cancel-participants').show();
        if(diffItems != 49) {
            $('#save-participants').show();
        }
        alert("{{$_POST['nick']}}");

        // This is the code's place to add item automatically and the key is $_POST['nick']
    @endif

Thank you.
Sorry for bad english

 

 

————————————————-

Answer

You can add options to existing selectize by following approach:

$(document).ready(function(){
    var selectize_element = $("#select-links")[0].selectize;
     selectize_element.addOption({
        text:'First Item',
        value: 'First Item'
    });
    selectize_element.refreshOptions() ;
    selectize_element.addItem('First Item');
});

javascript,jquery

Facebook Comments

Post a comment