javascript - Select2 - use JSON as local data -
i can work...
var options = [{id: 1, text: 'adair, charles'}] $('#names').select2({ data: options, })
but cant work out how here...
alert(json.stringify(request.names)) gives me...
[{"id":"1","name":"adair,james"}, {"id":"2","name":"anderson,peter"}, {"id":"3","name":"armstrong,ryan"}]
to select2 accept local data
load data local array
the webpage of jquery-select2 examples contains demo 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 question example e10_2
relevant
<input type="hidden" id="e10_2" style="width:300px"/>
to achive need function format()
seen below:
$(document).ready(function() { // tell select2 use property name 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 output:
hint
to see source code of each example best use network tab of chrome dev tools , take of html source before javascript kicks in.
Comments
Post a Comment