selectize js use array as source
Asked Answered
S

2

9

Hi I am getting back a JSON encoded array ("html") from my Ajax call that I would like to add in the selectize as both value and text (I am using a tag) . How can I do that ?

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
                }
            }
        });

}

Sheley answered 8/10, 2013 at 0:12 Comment(0)
A
14

You could map the array onto an array of objects, like this:

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

Then use "labelField" and "valueField" to specify the text/value:

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

Fiddle Demo.

Abroms answered 8/10, 2013 at 0:28 Comment(1)
FYI, you probably need to add searchField: ['item'], after that.Generator
P
2

With ES6 you can reduce your oneliner a bit

const items = data.map(item => ({item}));
Pelting answered 22/11, 2017 at 10:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.