How to add dynamically options in selectize select using ajax
In this tutorial I will show the code you need to create in order to add options to your selectize select using ajax. Even if selectize has a lot of documentation this is not easy using to implement using it maybe it more easier to implement some features if you look directly in the source code of the plugin. That being said let's start with the implementation of this functionality. First of all we need to create the HTML for the select.
All code we need for dynamically options
<select id="selectize_container"></select>
The select is empty all options will be added in our ajax function with items where comes from server.
Then let's create the js part, in the below tutorial I will add all the options at click event but you can change it and use it as you need.
$body.on('click', '.my_button', function(e){ e.preventDefault(); var element = jQuery('#selectize_container'); if(element[0].selectize){ element[0].selectize.destroy(); } element.selectize({ labelField: 'title', valueField: 'id', hideSelected:true, persist:false, create: false, placeholder: "Dynamically options", render: { item: function(item, escape) { return "<div><img src=" + escape(item.img) + "><span>" + escape(item.title) + "</span></div>"; }, option: function(item, escape) { return "<div><img src=" + escape(item.img) + "><span>" + escape(item.title) + "</span></div>"; } }, }); jQuery.ajax({ type:"POST", url:'/get-my-options', data:{}, success:function(result){ var selectize = element[0].selectize; var my_data = result.data; if(my_data.length){ for(var i=0;i < my_data.length;i++){ var item = my_data[i]; var data = { 'id':item.id, 'title':item.title, 'img':item.image }; selectize.addOption(data); selectize.refreshOptions(); } } }, error:function(error){ console.log(error); } }); });
The above function will do all the things we need to add options dynamically. I tried a lot of methods to implement this feature, and this method is the only one which worked for me. In the above code before init the selectize I check if it is already initialized if so I destroy it and then append the new options to the selectize. addOptions() and refreshOptions() will do the trick for you if you pass corectly the object with the new values. Let me know how this method worked for you.