Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using select2 with json data that doesn't have a field called "text" while avoiding copying the items and loosing standard behaviors

I'm using select2 and I want to set a custom field for the text property of the rendered items without

  • replacing standard behavior (marking and such)
  • pushin all my array into a new one with the text field on it
    • ps: i just want to a render many select2 items that doesn't have a text field

Basically if you see this jsbin you will see something like this

$("#e10_3").select2({
    data:{ results: data, text: function(item) { return item.tag; } },
    formatSelection: format,
    formatResult: format
});

But if I delete the custom formatSelection and formatResult parameters of select2 I loose my hability to use a different field for text.

like image 220
genuinefafa Avatar asked Oct 20 '22 17:10

genuinefafa


1 Answers

I suggest this approach

$("#e10_3").select2({
    data:{
        results:  function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.tag,
                        id: item.id
                        ...
                    }
                })
            };
        }
    },
    formatSelection: format,
    formatResult: format
});
like image 69
Tolo Palmer Avatar answered Oct 24 '22 00:10

Tolo Palmer