I m working with a project using an AJAX call and in my program I have a select list and I need to implement select2 but I can not do it. My code in my .js file is:
function selectAlumnos(){
$.ajax({
type : "GET",
url : lang + '../../../api/select_alumnos', //the list of data
dataType : "json",
data : {
cachehora : (new Date()).getTime()
}
}).done(function(response){
var html = '';
if(response.state == 'ok'){ //add html to the file view
html = '<select class="select_1" name="select-allalumnos" id="select-allalumnos" onchange="getIconLocation()" >'; //class to include in select2
html = html + '<option value="-1">...</option>';
for(var i in response.alumnos){
html = html + '<option value="' + response.alumnos[i].id + '" >' + response.alumnos[i].nombre + '</option>';
} //get the list of the data
html = html + '</select>'; // put the data in the list
}
$('#select-alumnos').html(html); //publish the info in the html file
});
}
In my html page for the view I have the select-alumnos part like this:
<label for="select-alumnos" class="select">Alumno:</label>
<span id="select-alumnos"></span> //here is the call in the AJAX
In this file (html for view) I have also put all the select2 paths to the required files, and I checked all the files are ok, also I have included the class (same class in my js file):
$(document).ready(function() {
$(".select_1").select2();
});
</script>
What am I doing wrong because I can not get the select2 format in my list...?
you're calling select2()
on .select_1
before its created. Do it after you've created the element (put it in the done function)
.done(function(response){
var html = '';
if(response.state == 'ok'){ //add html to the file view
html = '<select class="select_1" name="select-allalumnos" id="select-allalumnos" onchange="getIconLocation()" >'; //class to include in select2
html = html + '<option value="-1">...</option>';
for(var i in response.alumnos){
html = html + '<option value="' + response.alumnos[i].id + '" >' + response.alumnos[i].nombre + '</option>';
} //get the list of the data
html = html + '</select>'; // put the data in the list
}
$('#select-alumnos').html(html); //publish the info in the html file
$(".select_1").select2();
});