i'm using Select2 in my project, but i can't get to work the initselect. I need to initialize the select2 with a default value.
this is the js:
function format(item) { return item.text; }
var jresults;
$.getJSON("ajax_select2.php?w=programma_rpp").done(
function( data ) {
$.jresults = data;
$("#programma_rpp").select2({
placeholder: "Seleziona un opzione",
allowClear: true,
formatResult: format,
formatSelection: format,
data: $.jresults,
initSelection: function (element, callback) {
callback({id: '1', text: 'testtext' });
}
}
);
}
)
The php page return this json:
[{"id":"1","text":"1 Programma 1 : Organizzazione E Gestione Servizi Generali"},{"id":"2","text":"2 Programma 2 : Difesa E Sicurezza Del Cittadino"},{"id":"3","text":"3 Programma 3 : Pubblica Istruzione Ed Opportunita' Culturali, Sportive E Ricreative"},{"id":"4","text":"4 Programma 4 : Tutela Dell'ambiente E Gestione Del Territorio E Del Patrimonio"},{"id":"5","text":"5 Programma 5 : Manutenzione Patrimonio Comunale, Viabilità E Trasporti"},{"id":"6","text":"6 Programma 6 : Servizi Alla Persona E Adeguamento Delle Strutture Sociali"},{"id":"7","text":"7 Programma 7 : Servizi Produttivi Ed Interventi Nel Campo Dello Sviluppo Economico"},{"id":"8","text":"8 Programma 8 : Programma Degli Investimenti"}]
I got no error in firebug but the select2 doesen't have any initial value. I read similar (but different somehow) problems on stackoverflow but none of the proposed solution work for me.
Thank you in advance, kind regards
After some research i come up with this solution:
$('programma_rpp').select2({
placeholder: 'Seleziona..',
minimumInputLength: 0,
allowClear: true,
multiple: false,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: 'ajax_select2.php?w=programma_rpp',
dataType: 'json',
data: function (term) {
return { q: term }; //search term
},
results: function (data) {
return { results: data};
}
},
});
And for initialize the value i use this
$('#programma_rpp').select2("data", {"id":"1","text":"1 Programma 1 : Organizzazione E Gestione Servizi Generali"} );
All works fine, i hope it can help someone else.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.