JQuery select2 set default value from an option in list?

前端 未结 10 783
傲寒
傲寒 2020-12-04 13:07

I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.

10条回答
  •  日久生厌
    2020-12-04 13:38

    Came from the future? Looking for the ajax source default value ?

    // 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
            }
        });
    });
    

    You're welcome.

    Reference: https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2

提交回复
热议问题