Select2 - use JSON as local data
Asked Answered
P

4

20

I can get this to work...

var options = [{id: 1, text: 'Adair, Charles'}]  
$('#names').select2({
    data: options,
})

But i cant work out how to get from here...

alert(JSON.stringify(request.names)) gives me...

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

To something that Select2 will accept as local data

Plebiscite answered 10/8, 2013 at 11:22 Comment(2)
What is this Select2 , can you explain more?Gregor
Select2: ivaynberg.github.io/select2Plebiscite
V
23

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:

Select2 - pimp my selectbox

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.

Vallonia answered 10/8, 2013 at 13:9 Comment(6)
Thanks, I actually had 2 errors going on which was stumping me, The formatting that you pointed out was missing and also var names = jQuery.parseJSON(optionString); was needed to get the JSON string into an object which select2 would use. Thanks again.Plebiscite
Glad i could help. A tip for the future: if you have more code it is good to include it in your question. This helps others to help you faster. Also if you have error-messages from chrome dev tools (see my profile for a link) it is very good to include them as well.Vallonia
Thanks for the tips, however I am more of a firebug man myself.Plebiscite
Where can I find the keys for data attribute there like results, or nameValois
Can you please post a working fiddle for load data if your array has no text property? Because, I get no results found even after copy/paste of your code.Borroff
The 2nd sample has the array "names" which has no text property.Vallonia
E
4

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));
});
Epistasis answered 6/3, 2017 at 20:59 Comment(0)
J
3

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.

Jehovist answered 22/4, 2016 at 6:46 Comment(0)
C
0

Example of select2 to handle big array. I am fetching data from server using ajax. Handling searching and pagination locally with more than 20000 data json.

<select id="widget_project"></select>


<script>
    $(function () {
        allProjects;// having all project json data using ajax
        
        pageSize = 50
        jQuery.fn.select2.amd.require(["select2/data/array", "select2/utils"],

        function (ArrayData, Utils) {
            function CustomData($element, options) {
                CustomData.__super__.constructor.call(this, $element, options);
            }
            Utils.Extend(CustomData, ArrayData);

            CustomData.prototype.query = function (params, callback) {

                var results = [];
                if(p_term !== "" &&  typeof params.term === "undefined"){
                    params.term = p_term;
                    console.log(params.term); 
                }
                if (params.term && params.term !== '') {
                    p_term = params.term;
                  results = findItem(params.term);
                } else {
                  results = allProjects;
                }

                if (!("page" in params)) {
                    params.page = 1;
                }
                var data = {};
                data.results = results.slice((params.page - 1) * pageSize, params.page * pageSize);
                data.pagination = {};
                data.pagination.more = params.page * pageSize < results.length;
                callback(data);
            };

            $(document).ready(function () {
                $("#widget_project").select2({
                    minimumInputLength: 3,
                    placeholder:"Select a project",
                    ajax: {},
                    dataAdapter: CustomData
                });
            });
        })
    });

</script>
Combustor answered 23/4, 2022 at 4:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.