无法设置select2的值

问题描述 投票:0回答:1

我已经初始化了一个select2

<select id="InputProjectName" class="form-control required"></select>

用通过 AJAX 请求生成的列表填充它。 它有一个搜索选项,输入几个字符后,它会显示这些记录的列表。 我想在初始化后设置一个值,而不是

search.$("#InputProjectName").val(95) 

$("#InputProjectName").val([95]) 

不起作用;

$("#InputProjectName").select2({
        allowClear: true,
        tags: true,
        placeholder: 'Lütfen seçiniz',
        minimumInputLength: 1,
        tokenSeparators: [','],
        multiple: true,
        maximumSelectionLength: 1,
        createTag: function (tag) {
            let term = $.trim(tag.term);
            if (term.length < 3) {
                return null
            }
        },
        ajax: {
            url: "/Project/GetProject",
            dataType: 'json',
            type: "POST",
            delay: 750,
            data: function (params) {
                return {
                    projectName: params.term,
                    recordId: params.term,
                    page: params.page
                };
            },
            processResults: function (data, params) {
                params.page = params.page || 1;

                var items = [];

                for (var i in data) {
                    var item = data[i];
                    items.push({ id: item.Id, text: 'Id:' + item.Id + ' -Name:' + item.ProjectName });
                }

                return {
                    results: items
                };
            },
            cache: true
        },

    }).on('select2:select', function (e) {

        var selectedValueArray = $("#InputProjectName").val();
        if (selectedValueArray) {
            var selectedValue = selectedValueArray[0];
            GetFillList($("#InputItem"), '/Project/GetQuestion/', selectedValue);

        }

    }).on("select2:unselecting", function (e) {
        //$("#InputItem").val(null).trigger("change");
    });
});

提前致谢。

javascript jquery ajax jquery-select2
1个回答
0
投票
// Assuming you know the ID and the text of the option you want to set
var idToSet = 95;
var textToSet = "Example Project Name"; // You should replace this with the actual project name

// Check if the option already exists
if ($("#InputProjectName").find("option[value='" + idToSet + "']").length === 0) {
    // If the option doesn't exist, create it and append it to the select element
    var newOption = new Option(textToSet, idToSet, true, true);
    $("#InputProjectName").append(newOption).trigger('change');
}

// Now set the value and trigger the change event to update the Select2 display
$("#InputProjectName").val(idToSet).trigger('change');

// This ensures the new option is selected and displayed by the Select2 control
© www.soinside.com 2019 - 2024. All rights reserved.