I am having problems trying to fill a dropdown (select) with select2 from a remote resource:
I fixed my backend code so that the API returns the following JSON code:
[
{"id":9,"nombre":"Jose"},
{"id":10,"nombre":"Juan"},
{"id":11,"nombre":"Rodrigo"},
{"id":12,"nombre":"Martin"},
{"id":3,"nombre":"Pablo"},
{"id":4,"nombre":"Eduardo"},
{"id":5,"nombre":"Fernando"},
{"id":13,"nombre":"Sebastian"}
]
On the other hand, I have fields that are added dynamically by clicking a " Add " button. To fill each select2 with the same results the best way I found is:
$('#agregar').click(function (e) {
e.preventDefault();
...
$('#nombre_${id}').select2({
ajax: {
url: '/api/nombres',
processResults: function (data) {
return {
// ¿qué va acá?
};
}
},
language: 'es',
});
Just in case, there are some examples but they are not specific: link
How should I call the API to show me the results as <option value={id}>{nombre}</option>
in select2?
Thank you very much.
Edition 1:
I have tried this example but I do not load the select2 directly, I know that the use of async: false
is obsolete, but it does not load the dropdown. So load an empty dropdown (can you display a list but it does not have a name of the options ...?):
$.ajax({
url: '/api/nombres',
method: 'GET',
async: false,
success: function (data) {
$('#nombre_${id}').select2({
data: data,
language: 'es'
});
}
});