I am trying to use select2 for the first time.
I would like to have my data from a static array. Can you please help me?
Here is my code:
$(document).ready(function() {
var names = [{"id":"1","name":"Adair,James"}
, {"id":"2","name":"Anderson,Peter"}
, {"id":"3","name":"Armstrong,Ryan"}];
$("#e10_2").select2({
processResults: function(){
return {
results: $.map(names, function(obj) {
return { id: obj.id, text: obj.name };
})
};
}
});
});
You could use data option to pass an array to the select2 as :
$("#e10_2").select2({ data: names });
If you don't have text attribute adapt your array check the part of documentation made for this purpose The id and text properties are strictly enforced, e.g :
$(function () {
var names = [{"id":"1","name":"Adair James"}
, {"id":"2","name":"Anderson Peter"}
, {"id":"3","name":"Armstrong Ryan"}];
var data = $.map(names, function (obj) {
obj.id = obj.id;
obj.text = obj.name;
return obj;
});
$("select").select2({width: '100%',data: data});
});
Hope this helps.
$(function () {
var names = [{"id":"1","name":"Adair James"}
, {"id":"2","name":"Anderson Peter"}
, {"id":"3","name":"Armstrong Ryan"}];
var data = $.map(names, function (obj) {
obj.id = obj.id;
obj.text = obj.name;
return obj;
});
$("select").select2({width: '100%',data: data});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>
<link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet"/>
<select></select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With