bootstrap select2怎么设置默认值

2025-05-08 20:58:14
推荐回答(2个)
回答1:

// Set up the Select2 control
$('#mySelect2').select2({
    ajax: {
        url: '/api/students'
    }
});
// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
    type: 'GET',
    url: '/api/students/s/' + studentId
}).then(function (data) {    
// create the option and append to Select2
    var option = new Option(data.full_name, data.id, true, true);
    studentSelect.append(option).trigger('change');    
    // manually trigger the `select2:select` event
    studentSelect.trigger({
        type: 'select2:select',
        params: {
            data: data
        }
    });
});

回答2:

动态删除select中的所有options:document.getElementById("ddlResourceType").options.length=0;动态删除select中的某一项option:document.getElementById("ddlResourceType").options.remove(indx);动态添加select中的项option:documen