如何设置 jQuery Select2 的选定值?
这属于 Select2 版本 4 之前的代码
This belong to codes prior to Select2 version 4
我有一个从 AJAX 获取数据的 select2
简单代码.
I have a simple code of select2
that get data from 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
) 中以选择先前选择的值但我找不到一种方式.
This code is working, however, I need to set a value on it as if in edit mode. When user select a value first time, it will be saved and when he needs to edit that value it must appear in the same select menu (select2
) to select the value previously selected but I can't find a way.
更新:
HTML 代码:
<input type="hidden" name="programid" id="programid" class="width-500 validate[required]">
Select2 编程访问 不适用于此.
动态设置 Select2 组件的selected"值:
To dynamically set the "selected" value of a Select2 component:
$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});
其中第二个参数是具有预期值的对象.
Where the second parameter is an object with expected values.
更新:
这确实有效,只是想注意在新的 select2 中,"a_key" 是标准 select2 对象中的 "text".所以:{id: 100, text: 'Lorem Ipsum'}
This does work, just wanted to note that in the new select2, "a_key" is "text" in a standard select2 object. so: {id: 100, text: 'Lorem Ipsum'}
示例:
$('#all_contacts').select2('data', {id: '123', text: 'res_data.primary_email'});
感谢@NoobishPro