Select js to use array as source

Hey. I am returning a JSON-encoded array ("html") from my Ajax call, which I would like to add both value and text to selectize (I use a tag). How can i do this?

HTML

<input type="text" value="test" class="demo-default selectized" id="input-tags" tabindex="-1" style="display: block;"> 

JQuery

 try { data = $.parseJSON(html); var obj = jQuery.parseJSON(html); outcome = (obj.outcome); $('#input-tags').selectize({ delimiter: ',', persist: false, maxItems: 1, create: function (input) { return { value: input, text: input } } }); 

}

+7
javascript jquery jquery-plugins
source share
2 answers

You can map an array to an array of objects, for example:

 data = $.parseJSON(html); var items = data.map(function(x) { return { item: x }; }); 

Then use "labelField" and "valueField" to indicate text / value:

 $('#input-tags').selectize({ delimiter: ',', persist: false, options: items, labelField: "item", valueField: "item" }); 

Screenshot Demo.

+11
source share

With ES6 you can slightly reduce your oneliner

 const items = data.map(item => ({item})); 
+1
source share

All Articles