如何设置 jQuery Select2 的选定值?

157

这段代码属于 Select2 版本 4 之前的代码。

我有一个简单的 select2 代码,它从 AJAX 获取数据。

$("#programid").select2({
  placeholder: "Select a Program",
  allowClear: true,
  minimumInputLength: 3,
  ajax: {
    url: "ajax.php",
    dataType: 'json',
    quietMillis: 200,
    data: function (term, page) {
      return {
        term: term, //search term
        flag: 'selectprogram',
        page: page // page number
      };
    },
    results: function (data) {
      return {results: data};
    }
  },
  dropdownCssClass: "bigdrop",
  escapeMarkup: function (m) { return m; }
});

这段代码是可行的,但是我需要在编辑模式下设置一个值。当用户第一次选择一个值时,它将被保存,当他需要编辑该值时,它必须出现在相同的下拉菜单(select2)中以选择先前选择的值,但我找不到方法。

更新:

HTML代码:

<input type="hidden" name="programid" id="programid" class="width-500 validate[required]">

Select2编程访问在这里无法正常工作。


你应该能够在HTML中设置所选的值,或者使用$("#programid").val() - Explosion Pills
@ExplosionPills 不行,我也试过了,我得到了一个空值。我应该如何使用programid.val()?我从服务器获取了值,然后需要将其设置到select2的隐藏字段中。 - ClearBoth
@ClearBoth 不确定我是否理解你的意思。你是想将Select2组件的"selected"值设置为AJAX检索到的结果之一吗? - An Phan
@AnPhan 是的,有方法可以做到吗? - ClearBoth
@ClearBoth 这里有。请查看我下面的答案。 - An Phan
35个回答

0
如果您正在使用输入框,必须将"multiple"属性设置为"true"。例如:
<script>
    $(document).ready(function () {

        var arr = [{ id: 100, text: 'Lorem Ipsum 1' },
            { id: 200, text: 'Lorem Ipsum 2'}];

        $('#inputID').select2({
            data: arr,
            width: 200,
            multiple: true
        });
    });
</script>

0
这可能会帮助那些在加载用于编辑的select2数据时使用AJAX的人(适用于单选或多选):
在我的表单/模型加载期间:
  $.ajax({
        type: "POST",
        ...        
        success: function (data) {
          selectCountries(fixedEncodeURI(data.countries));
         }

调用以选择 Select2 数据:

var countrySelect = $('.select_country');
function selectCountries(countries)
    {
        if (countries) {
            $.ajax({
                type: 'GET',
                url: "/regions/getCountries/",
                data: $.param({ 'idsSelected': countries }, true),

            }).then(function (data) {
                // create the option and append to Select2                     
                $.each(data, function (index, value) {
                    var option = new Option(value.text, value.id, true, true);
                    countrySelect.append(option).trigger('change');
                    console.log(option);
                });
                // manually trigger the `select2:select` event
                countrySelect.trigger({
                    type: 'select2:select',
                    params: {
                        data: data
                    }
                });
            });
        }
    }

如果您在编码方面遇到问题,可以根据您的要求进行更改:

function fixedEncodeURI(str) {
        return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/%22/g,"");

    }

-1

如果您从ajax获取值,请在调用之前

$("#select_location_id").val(value);
$("#select_location_id").select2().trigger('change');

确认ajax调用已完成,使用jQuery函数when。

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
      // the code here will be executed when all four ajax requests resolve.
      // a1, a2, a3 and a4 are lists of length 3 containing the response text,
      // status, and jqXHR object for each of the four ajax calls respectively.
    }); 

as described here [Wait until all jQuery Ajax requests are done?


-1
在收到您的请求后,您可以通过以下方式更新select2的值:
let response = JSON.parse(your_response);
let key_to_select = response.your_key;

$(document).find('yourIdorClass').val(key_to_select ).trigger("change");

-4

简单易懂:

document.getElementById("select2-id_city-container").innerHTML = "Your Text Here";

你需要将 id_city 更改为你的选择器的 id。

编辑:在 Glen 的评论之后,我意识到我应该解释一下为什么以及如何让它对我起作用:

我已经让 select2 在我的表单中非常好地工作了。唯一无法实现的是在编辑时显示当前选定的值。它正在搜索第三方 API,保存新记录和编辑旧记录。过了一会儿,我意识到我不需要正确设置值,只需要设置字段内部的标签,因为如果用户不更改字段,则不会发生任何事情。在搜索并查看了很多遇到问题的人之后,我决定使用纯 JavaScript 来实现它。它起作用了,我发布了这篇文章,希望能帮助到某些人。我还建议为其设置一个计时器。


这个答案是一个可怕的黑客,甚至不能正确设置值。 - Glen
很抱歉。我会编辑我的回答并解释为什么发布它。 - bonafernando

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接