Select2 - use JSON as local data

纵饮孤独 提交于 2019-11-29 03:19:09

Load data from a local array

The webpage of with the examples contains a demo to use Select2 with local data (an array).

The html

<input type="hidden" id="e10" style="width:300px"/>

The javascript

$(document).ready(function() { 

    var sampleArray = [{id:0,text:'enhancement'}, {id:1,text:'bug'}
                       ,{id:2,text:'duplicate'},{id:3,text:'invalid'}
                       ,{id:4,text:'wontfix'}];

    $("#e10").select2({ data: sampleArray });

});

Select2 load data if array has no text property

For your question the example e10_2 is relevant

<input type="hidden" id="e10_2" style="width:300px"/>

To achive that you need the function format() as seen below:

$(document).ready(function() { 

    // tell Select2 to use the property name for the text
    function format(item) { return item.name; };

    var names = [{"id":"1","name":"Adair,James"}
             , {"id":"2","name":"Anderson,Peter"}
             , {"id":"3","name":"Armstrong,Ryan"}]

    $("#e10_2").select2({
            data:{ results: names, text: 'name' },
            formatSelection: format,
            formatResult: format                        
    });

});

This is the output:

Hint

To see the source code of each example it is best to use the network tab of the chrome dev tools and take a look of the html source before javascript kicks in.

Just to add. This also worked for me:

HTML:

<select id="names" name="names" class="form-control"></select>

Javascript

$('#names').select2();

var options = $('#names');

$.each(sampleArray, function() {
    options.append($("<option />").val(this.id).text(this.name));
});
DotNetBeliever

As an update for this old post, having custom properties for id and text is not directly supported anymore since 4.0.0+ version.

See here on "The id and text properties are strictly enforced" text block. You must create a $.map object as a workaround.

Even more, working with an [input type="hidden"] is now deprecated as all core select2 options now support the [select] html object.

Have a look to John S' answer on this post as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!