如何设置 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个回答

7
我认为你需要使用initSelection函数。
$("#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};
    }
  },
  initSelection: function (element, callback) {
    var id = $(element).val();
    if (id !== "") {
      $.ajax("ajax.php/get_where", {
        data: {programid: id},
        dataType: "json"
      }).done(function (data) {
        $.each(data, function (i, value) {
          callback({"text": value.text, "id": value.id});
        });
        ;
      });
    }
  },
  dropdownCssClass: "bigdrop",
  escapeMarkup: function (m) { return m; }
});

这个可以工作。但是自4.0版本起已经被弃用了。 - VisualBean

6

对于Ajax,使用$(".select2").val("").trigger("change")。这样应该就解决了问题。


我希望我能点赞一千次...你救了我。 - stephen waweru99

6

Select2 V.4 中,使用以下代码可以选择值并触发更改事件:

$('selector').select2().val(value_to_select).trigger('change');

我认为这应该可以正常工作。


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

我用这段简单的代码解决了我的问题。其中 #select_location_id 是一个选择框的ID,value是在select2框中列出的选项的值。

2
有时,select2() 会首先加载,这会使控件无法正确显示之前选择的值。延迟几秒钟可以解决这个问题。
setTimeout(function(){                  
    $('#costcentreid').select2();               
},3000);

2

An Phan的答案对我有用:

$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});

但是添加变化会触发事件。

$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'}).change();

1
当我这样做时,我会收到错误消息“Uncaught TypeError: $(...).select2(...).change is not a function(…)”。我认为在Select2的4.x版本中不可能使用此方法 - 这里没有任何与ajax相关的内容。 - MC9000

2
这对我来说很有效:
        initSelection: function (element, callback) {
    var id = $(element).val();
    $.ajax("url/" + id, {
        dataType: "json"
    }).done(function (data) {
        var newOption = new Option(data.title, data.id, true, true);
        $('#select2_id').append(newOption).trigger('change');
        callback({"text": data.title, "id": data.id});
    });
},

2
你可以使用以下代码:
$("#programid").val(["number:2", "number:3"]).trigger("change");

"number:2"和"number:3"中的2和3是对象数组中的id字段


1
您可以使用这段代码:

    $('#country').select2("val", "Your_value").trigger('change');

请将"Your_value"替换为您想要的值。
希望这能起作用 :)

1

官方Select2文档表示:

对于从AJAX源接收数据的Select2控件,使用.val() 将不起作用。选项尚不存在,因为AJAX请求在打开控件和/或用户开始搜索之前不会触发。

要在select2字段中设置值,请在页面呈现期间将<option>标签放置在<select>标签中:

<select id="input-degree">
    <option value="1">Art</option>
</select>

当页面加载时,您将在select2字段中看到Art。如果单击此字段,数据将通过ajax从服务器获取,并显示其他选项。

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