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?
答案 0 :(得分:0)
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']));
}
}
});
答案 1 :(得分:0)
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);
}
答案 2 :(得分:0)
如果您收到多个以逗号分隔的值,则可以使用此select2
技巧设置值:
var makeArray = commanSeparatedValues.split(',');
$('#SELECT_ID').val(makeArray);
使用select2
时,您应该使用这个很酷的小技巧。避免循环和$.each
。希望这有帮助!
答案 3 :(得分:0)
看看 https://select2.org/programmatic-control/add-select-clear-items 用于通过 js 向 select2 添加选项