Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - Select2 - use JSON as local data

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...