i need to append to a select2 multiple, some results fetched from ajax. I try to achieve this result using this code:
<select name='prodotti' rows='5' multiple id='prodotti' class='select2'></select>
Here is JS
$('#close-modal').on('click', function (e) {
var id = $('#id').val();
$.ajax({
type: 'GET',
url: '/items-fattura?id=' + id,
success: function (response) {
$("#prodotti").val(response);
}
});
});
Ajax return this results:
[{"id":2,"nome":"Certificato SSL POSITIVE"}]
Can someone help me to resolve?
You can try this.
$.ajax({
type: 'GET',
url: '/items-fattura?id=' + id,
success: function (response) {
var $el = $("#prodotti");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", 0)
.text('Select'));
for (i = 0; i < response.length; i++) {
$el.append($("<option></option>")
.attr("value", response[i]['id'])
.text(response[i]['name']));
}
}
});
Use $.each to iterate through your JSON array that you receive from ajax call.
Note:- the spelling of success
, you have written sucess
.
success: function(data){
data = JSON.parse(data);
var toAppend = '';
$('#prodotti').empty();
$.each(data, function(i,o){
toAppend += '<option value="'+ o.nome +'">'+o.id+'</option>';
});
$('#prodotti').append(toAppend);
}
If you receiving multiple values that are separated by comma, you can use this select2
trick to set the values:
var makeArray = commanSeparatedValues.split(',');
$('#SELECT_ID').val(makeArray);
It's an nifty little cool trick that you should use when working with select2
. Avoiding the loops and $.each
. Hope this helps!
看看https://select2.org/programmatic-control/add-select-clear-items以通过 js 向 select2 添加选项
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.