使用AJAX时如何设置Select2的初始值?
How can I set the initial value of Select2 when using AJAX?
我有一个从 Ajax 数组填充的 select2 v4.0.0。如果我设置 select2 的值,我可以通过 javascript 调试看到它 selected 了正确的项目(在我的例子中是#3),但是这没有显示在select 框,它仍然显示占位符。
而我应该看到这样的东西:
在我的表单字段中:
<input name="creditor_id" type="hidden" value="3">
<div class="form-group minimal form-gap-after">
<span class="col-xs-3 control-label minimal">
<label for="Creditor:">Creditor:</label>
</span>
<div class="col-xs-9">
<div class="input-group col-xs-8 pull-left select2-bootstrap-prepend">
<select class="creditor_select2 input-xlarge form-control minimal select2 col-xs-8">
<option></option>
</select>
</div>
</div>
</div>
我的javascript:
var initial_creditor_id = "3";
$(".creditor_select2").select2({
ajax: {
url: "/admin/api/transactions/creditorlist",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
c_id: initial_creditor_id,
page: params.page
};
},
processResults: function (data, page) {
return {
results: data
};
},
cache: true
},
placeholder: "Search for a Creditor",
width: "element",
theme: "bootstrap",
allowClear: true
}).on("select2:select", function (e) {
var selected = e.params.data;
if (typeof selected !== "undefined") {
$("[name='creditor_id']").val(selected.creditor_id);
$("#allocationsDiv").hide();
$("[name='amount_cash']").val("");
$("[name='amount_cheque']").val("");
$("[name='amount_direct']").val("");
$("[name='amount_creditcard']").val("");
}
}).on("select2:unselecting", function (e) {
$("form").each(function () {
this.reset()
});
("#allocationsDiv").hide();
$("[name='creditor_id']").val("");
}).val(initial_creditor_id);
如何让 select 框显示 selected 项目而不是占位符?我应该将其作为 AJAX JSON 响应的一部分发送吗?
过去,Select2 需要一个名为 initSelection 的选项,该选项在使用自定义数据源时定义,从而允许确定组件的初始 selection。这在 v3.5 中对我来说效果很好。
你做的大部分事情都是正确的,看起来你遇到的唯一问题是你在设置新值后没有触发 change
方法。如果没有 change
事件,Select2 无法知道基础值已更改,因此它只会显示占位符。将你的最后一部分更改为
.val(initial_creditor_id).trigger('change');
应该可以解决您的问题,您应该会立即看到 UI 更新。
这是假设您的 <option>
已经有一个 value
为 initial_creditor_id
。如果您不选择 Select2,浏览器实际上将无法更改该值,因为没有可切换到的选项,并且 Select2 不会检测到新值。我注意到您的 <select>
只包含一个选项,即占位符选项,这意味着您需要手动创建新的 <option>
。
var $option = $("<option selected></option>").val(initial_creditor_id).text("Whatever Select2 should display");
然后将其附加到您初始化 Select2 的 <select>
。您可能需要从外部来源获取文本,这是 initSelection
曾经发挥作用的地方,这在 Select2 4.0.0 中仍然是可能的。与标准 select 一样,这意味着您必须发出 AJAX 请求来检索值,然后即时设置 <option>
文本进行调整。
var $select = $('.creditor_select2');
$select.select2(/* ... */); // initialize Select2 and any events
var $option = $('<option selected>Loading...</option>').val(initial_creditor_id);
$select.append($option).trigger('change'); // append the option and update Select2
$.ajax({ // make the request for the selected data object
type: 'GET',
url: '/api/for/single/creditor/' + initial_creditor_id,
dataType: 'json'
}).then(function (data) {
// Here we should have the data object
$option.text(data.text).val(data.id); // update the text that is displayed (and maybe even the value)
$option.removeData(); // remove any caching data that might be associated
$select.trigger('change'); // notify JavaScript components of possible changes
});
虽然这看起来可能有很多代码,但对于非 Select2 select 框,这 正是您的做法,以确保所有更改都已完成.
嗨几乎要退出并返回 select 3.5.1。但我终于得到了答案!
$('#test').select2({
placeholder: "Select a Country",
minimumResultsForSearch: 2,
ajax: {
url: '...',
dataType: 'json',
cache: false,
data: function (params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: data.items
};
}
}
});
var option1 = new Option("new",true, true);
$('#status').append(option1);
$('#status').trigger('change');
只需确保新选项是 select2 个选项之一。我通过 json.
得到这个
被迫 trigger('change')
的问题让我抓狂,因为我在 change
触发器中有自定义代码,它应该只在用户更改下拉列表中的选项时触发。 IMO,在开始时设置初始值时不应触发更改。
我深入挖掘并发现以下内容:https://github.com/select2/select2/issues/3620
示例:
$dropDown.val(1).trigger('change.select2');
我做的更干净,需要制作两个数组:
- 一个包含带有 id 和文本的对象列表(在我的例子中它的 id 和名称,取决于你的 templateResult)(它是你从 ajax 查询中得到的)
- 第二个只是一个id数组(选择值)
我使用第一个数组作为数据,第二个作为值来初始化 select2。
一个示例函数,其参数为 id:name 的字典。
function initMyList(values) {
var selected = [];
var initials = [];
for (var s in values) {
initials.push({id: s, name: values[s].name});
selected.push(s);
}
$('#myselect2').select2({
data: initials,
ajax: {
url: "/path/to/value/",
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term,
page: params.page || 1,
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
minimumInputLength: 1,
tokenSeparators: [",", " "],
placeholder: "Select none, one or many values",
templateResult: function (item) { return item.name; },
templateSelection: function (item) { return item.name; },
matcher: function(term, text) { return text.name.toUpperCase().indexOf(term.toUpperCase()) != -1; },
});
$('#myselect2').val(selected).trigger('change');
}
您可以使用 ajax 调用提供初始值,并使用 jquery 承诺进行 select2 初始化。
我添加这个答案主要是因为我无法在上面发表评论!我发现这是@Nicki 和她的 jsfiddle https://jsfiddle.net/57co6c95/ 的评论,最终让这个对我有用。
除其他外,它还提供了 json 所需的格式示例。我必须做的唯一改变是我的初始结果以与其他 ajax 调用相同的格式返回,所以我不得不使用
$option.text(data[0].text).val(data[0].id);
而不是
$option.text(data.text).val(data.id);
One scenario that I haven't seen people really answer, is how to have a preselection when the options are AJAX sourced, and you can select multiple.由于这是 AJAX preselection 的转到页面,我将在此处添加我的解决方案。
$('#mySelect').select2({
ajax: {
url: endpoint,
dataType: 'json',
data: [
{ // Each of these gets processed by fnRenderResults.
id: usersId,
text: usersFullName,
full_name: usersFullName,
email: usersEmail,
image_url: usersImageUrl,
selected: true // Causes the selection to actually get selected.
}
],
processResults: function(data) {
return {
results: data.users,
pagination: {
more: data.next !== null
}
};
}
},
templateResult: fnRenderResults,
templateSelection: fnRenderSelection, // Renders the result with my own style
selectOnClose: true
});
在花了几个小时寻找解决方案后,我决定创建自己的解决方案。他是:
function CustomInitSelect2(element, options) {
if (options.url) {
$.ajax({
type: 'GET',
url: options.url,
dataType: 'json'
}).then(function (data) {
element.select2({
data: data
});
if (options.initialValue) {
element.val(options.initialValue).trigger('change');
}
});
}
}
并且您可以使用此函数初始化选择:
$('.select2').each(function (index, element) {
var item = $(element);
if (item.data('url')) {
CustomInitSelect2(item, {
url: item.data('url'),
initialValue: item.data('value')
});
}
else {
item.select2();
}
});
当然,这里是 html:
<select class="form-control select2" id="test1" data-url="mysite/load" data-value="123"></select>
使用 select2 4.0.3
的初始选定值创建简单的 ajax 组合
<select name="mycombo" id="mycombo""></select>
<script>
document.addEventListener("DOMContentLoaded", function (event) {
selectMaker.create('table', 'idname', '1', $("#mycombo"), 2, 'type');
});
</script>
库.js
var selectMaker = {
create: function (table, fieldname, initialSelected, input, minimumInputLength = 3, type ='',placeholder = 'Select a element') {
if (input.data('select2')) {
input.select2("destroy");
}
input.select2({
placeholder: placeholder,
width: '100%',
minimumInputLength: minimumInputLength,
containerCssClass: type,
dropdownCssClass: type,
ajax: {
url: 'ajaxValues.php?getQuery=true&table=' + table + '&fieldname=' + fieldname + '&type=' + type,
type: 'post',
dataType: 'json',
contentType: "application/json",
delay: 250,
data: function (params) {
return {
term: params.term, // search term
page: params.page
};
},
processResults: function (data) {
return {
results: $.map(data.items, function (item) {
return {
text: item.name,
id: item.id
}
})
};
}
}
});
if (initialSelected>0) {
var $option = $('<option selected>Cargando...</option>').val(0);
input.append($option).trigger('change'); // append the option and update Select2
$.ajax({// make the request for the selected data object
type: 'GET',
url: 'ajaxValues.php?getQuery=true&table=' + table + '&fieldname=' + fieldname + '&type=' + type + '&initialSelected=' + initialSelected,
dataType: 'json'
}).then(function (data) {
// Here we should have the data object
$option.text(data.items[0].name).val(data.items[0].id); // update the text that is displayed (and maybe even the value)
$option.removeData(); // remove any caching data that might be associated
input.trigger('change'); // notify JavaScript components of possible changes
});
}
}
};
和php服务器端
<?php
if (isset($_GET['getQuery']) && isset($_GET['table']) && isset($_GET['fieldname'])) {
//parametros carga de petición
parse_str(file_get_contents("php://input"), $data);
$data = (object) $data;
if (isset($data->term)) {
$term = pSQL($data->term);
}else{
$term = '';
}
if (isset($_GET['initialSelected'])){
$id =pSQL($_GET['initialSelected']);
}else{
$id = '';
}
if ($_GET['table'] == 'mytable' && $_GET['fieldname'] == 'mycolname' && $_GET['type'] == 'mytype') {
if (empty($id)){
$where = "and name like '%" . $term . "%'";
}else{
$where = "and id= ".$id;
}
$rows = yourarrayfunctionfromsql("SELECT id, name
FROM yourtable
WHERE 1 " . $where . "
ORDER BY name ");
}
$items = array("items" => $rows);
$var = json_encode($items);
echo $var;
?>
如果您使用的是 templateSelection 和 ajax,其中一些其他答案可能无效。当您的数据对象使用 id 和文本以外的其他值时,似乎创建一个新的 option
元素并设置 value
和 text
将无法满足模板方法。
以下是对我有用的方法:
$("#selectElem").select2({
ajax: { ... },
data: [YOUR_DEFAULT_OBJECT],
templateSelection: yourCustomTemplate
}
在这里查看 jsFiddle:https://jsfiddle.net/shanabus/f8h1xnv4
在我的例子中,我不得不 processResults
输入,因为我的数据不包含必需的 id
和 text
字段。如果您需要这样做,您还需要通过相同的功能 运行 您的初始选择。像这样:
$(".js-select2").select2({
ajax: {
url: SOME_URL,
processResults: processData
},
data: processData([YOUR_INIT_OBJECT]).results,
minimumInputLength: 1,
templateSelection: myCustomTemplate
});
function processData(data) {
var mapdata = $.map(data, function (obj) {
obj.id = obj.Id;
obj.text = '[' + obj.Code + '] ' + obj.Description;
return obj;
});
return { results: mapdata };
}
function myCustomTemplate(item) {
return '<strong>' + item.Code + '</strong> - ' + item.Description;
}
对于简单的语义解决方案,我更喜欢在 HTML 中定义初始值,示例:
<select name="myfield" data-placeholder="Select an option">
<option value="initial-value" selected>Initial text</option>
</select>
因此,当我调用 $('select').select2({ ajax: {...}});
时,初始值为 initial-value
,其选项文本为 Initial text
。
我目前的Select2版本是4.0.3,但我认为它与其他版本的兼容性很好。
对我有用...
不要使用 jQuery,只使用 HTML:创建 选项值 您将显示为 selected.
如果 ID 在 select2 data 中,它将自动选择。
<select id="select2" name="mySelect2">
<option value="mySelectedValue">
Hello, I'm here!
</option>
</select>
https://github.com/select2/select2/issues/4272
只有这解决了我的问题。
即使您通过选项设置默认值,您也必须格式化具有文本属性的对象,这就是您想要在选项中显示的内容。
因此,您的格式函数必须使用 ||
来选择不为空的属性。
这是适用于我的多个 + 模板的解决方案:
(my ajax return 附加参数,“email”)
// my template
var my_template_func = function (data){
if( data.email )
var email = data.email;
else if( data.element )
var email = data.element.dataset.email;
var html = '<span><span>'+data.text+'</span> - <em>'+email+'</em></span>';
return $(html);
};
// select2 init
$('.my-select').select2({
ajax: {
url: '...',
dataType: 'json',
},
templateResult: my_template_func,
templateSelection: my_template_func,
});
然后我在 html
中设置默认选项
<option value="555" data-email="test@exemple.com" selected>Bob</option>
或者我用 JS 添加选项
// add option(s)
var option = new Option('Bob', 555, true, true);
option.dataset.email = 'test@exemple.com';
$('.my-select').append(option).trigger('change');
我有一个从 Ajax 数组填充的 select2 v4.0.0。如果我设置 select2 的值,我可以通过 javascript 调试看到它 selected 了正确的项目(在我的例子中是#3),但是这没有显示在select 框,它仍然显示占位符。
而我应该看到这样的东西:
在我的表单字段中:
<input name="creditor_id" type="hidden" value="3">
<div class="form-group minimal form-gap-after">
<span class="col-xs-3 control-label minimal">
<label for="Creditor:">Creditor:</label>
</span>
<div class="col-xs-9">
<div class="input-group col-xs-8 pull-left select2-bootstrap-prepend">
<select class="creditor_select2 input-xlarge form-control minimal select2 col-xs-8">
<option></option>
</select>
</div>
</div>
</div>
我的javascript:
var initial_creditor_id = "3";
$(".creditor_select2").select2({
ajax: {
url: "/admin/api/transactions/creditorlist",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
c_id: initial_creditor_id,
page: params.page
};
},
processResults: function (data, page) {
return {
results: data
};
},
cache: true
},
placeholder: "Search for a Creditor",
width: "element",
theme: "bootstrap",
allowClear: true
}).on("select2:select", function (e) {
var selected = e.params.data;
if (typeof selected !== "undefined") {
$("[name='creditor_id']").val(selected.creditor_id);
$("#allocationsDiv").hide();
$("[name='amount_cash']").val("");
$("[name='amount_cheque']").val("");
$("[name='amount_direct']").val("");
$("[name='amount_creditcard']").val("");
}
}).on("select2:unselecting", function (e) {
$("form").each(function () {
this.reset()
});
("#allocationsDiv").hide();
$("[name='creditor_id']").val("");
}).val(initial_creditor_id);
如何让 select 框显示 selected 项目而不是占位符?我应该将其作为 AJAX JSON 响应的一部分发送吗?
过去,Select2 需要一个名为 initSelection 的选项,该选项在使用自定义数据源时定义,从而允许确定组件的初始 selection。这在 v3.5 中对我来说效果很好。
你做的大部分事情都是正确的,看起来你遇到的唯一问题是你在设置新值后没有触发 change
方法。如果没有 change
事件,Select2 无法知道基础值已更改,因此它只会显示占位符。将你的最后一部分更改为
.val(initial_creditor_id).trigger('change');
应该可以解决您的问题,您应该会立即看到 UI 更新。
这是假设您的 <option>
已经有一个 value
为 initial_creditor_id
。如果您不选择 Select2,浏览器实际上将无法更改该值,因为没有可切换到的选项,并且 Select2 不会检测到新值。我注意到您的 <select>
只包含一个选项,即占位符选项,这意味着您需要手动创建新的 <option>
。
var $option = $("<option selected></option>").val(initial_creditor_id).text("Whatever Select2 should display");
然后将其附加到您初始化 Select2 的 <select>
。您可能需要从外部来源获取文本,这是 initSelection
曾经发挥作用的地方,这在 Select2 4.0.0 中仍然是可能的。与标准 select 一样,这意味着您必须发出 AJAX 请求来检索值,然后即时设置 <option>
文本进行调整。
var $select = $('.creditor_select2');
$select.select2(/* ... */); // initialize Select2 and any events
var $option = $('<option selected>Loading...</option>').val(initial_creditor_id);
$select.append($option).trigger('change'); // append the option and update Select2
$.ajax({ // make the request for the selected data object
type: 'GET',
url: '/api/for/single/creditor/' + initial_creditor_id,
dataType: 'json'
}).then(function (data) {
// Here we should have the data object
$option.text(data.text).val(data.id); // update the text that is displayed (and maybe even the value)
$option.removeData(); // remove any caching data that might be associated
$select.trigger('change'); // notify JavaScript components of possible changes
});
虽然这看起来可能有很多代码,但对于非 Select2 select 框,这 正是您的做法,以确保所有更改都已完成.
嗨几乎要退出并返回 select 3.5.1。但我终于得到了答案!
$('#test').select2({
placeholder: "Select a Country",
minimumResultsForSearch: 2,
ajax: {
url: '...',
dataType: 'json',
cache: false,
data: function (params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: data.items
};
}
}
});
var option1 = new Option("new",true, true);
$('#status').append(option1);
$('#status').trigger('change');
只需确保新选项是 select2 个选项之一。我通过 json.
得到这个被迫 trigger('change')
的问题让我抓狂,因为我在 change
触发器中有自定义代码,它应该只在用户更改下拉列表中的选项时触发。 IMO,在开始时设置初始值时不应触发更改。
我深入挖掘并发现以下内容:https://github.com/select2/select2/issues/3620
示例:
$dropDown.val(1).trigger('change.select2');
我做的更干净,需要制作两个数组:
- 一个包含带有 id 和文本的对象列表(在我的例子中它的 id 和名称,取决于你的 templateResult)(它是你从 ajax 查询中得到的)
- 第二个只是一个id数组(选择值)
我使用第一个数组作为数据,第二个作为值来初始化 select2。
一个示例函数,其参数为 id:name 的字典。
function initMyList(values) {
var selected = [];
var initials = [];
for (var s in values) {
initials.push({id: s, name: values[s].name});
selected.push(s);
}
$('#myselect2').select2({
data: initials,
ajax: {
url: "/path/to/value/",
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term,
page: params.page || 1,
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
minimumInputLength: 1,
tokenSeparators: [",", " "],
placeholder: "Select none, one or many values",
templateResult: function (item) { return item.name; },
templateSelection: function (item) { return item.name; },
matcher: function(term, text) { return text.name.toUpperCase().indexOf(term.toUpperCase()) != -1; },
});
$('#myselect2').val(selected).trigger('change');
}
您可以使用 ajax 调用提供初始值,并使用 jquery 承诺进行 select2 初始化。
我添加这个答案主要是因为我无法在上面发表评论!我发现这是@Nicki 和她的 jsfiddle https://jsfiddle.net/57co6c95/ 的评论,最终让这个对我有用。
除其他外,它还提供了 json 所需的格式示例。我必须做的唯一改变是我的初始结果以与其他 ajax 调用相同的格式返回,所以我不得不使用
$option.text(data[0].text).val(data[0].id);
而不是
$option.text(data.text).val(data.id);
One scenario that I haven't seen people really answer, is how to have a preselection when the options are AJAX sourced, and you can select multiple.由于这是 AJAX preselection 的转到页面,我将在此处添加我的解决方案。
$('#mySelect').select2({
ajax: {
url: endpoint,
dataType: 'json',
data: [
{ // Each of these gets processed by fnRenderResults.
id: usersId,
text: usersFullName,
full_name: usersFullName,
email: usersEmail,
image_url: usersImageUrl,
selected: true // Causes the selection to actually get selected.
}
],
processResults: function(data) {
return {
results: data.users,
pagination: {
more: data.next !== null
}
};
}
},
templateResult: fnRenderResults,
templateSelection: fnRenderSelection, // Renders the result with my own style
selectOnClose: true
});
在花了几个小时寻找解决方案后,我决定创建自己的解决方案。他是:
function CustomInitSelect2(element, options) {
if (options.url) {
$.ajax({
type: 'GET',
url: options.url,
dataType: 'json'
}).then(function (data) {
element.select2({
data: data
});
if (options.initialValue) {
element.val(options.initialValue).trigger('change');
}
});
}
}
并且您可以使用此函数初始化选择:
$('.select2').each(function (index, element) {
var item = $(element);
if (item.data('url')) {
CustomInitSelect2(item, {
url: item.data('url'),
initialValue: item.data('value')
});
}
else {
item.select2();
}
});
当然,这里是 html:
<select class="form-control select2" id="test1" data-url="mysite/load" data-value="123"></select>
使用 select2 4.0.3
的初始选定值创建简单的 ajax 组合<select name="mycombo" id="mycombo""></select>
<script>
document.addEventListener("DOMContentLoaded", function (event) {
selectMaker.create('table', 'idname', '1', $("#mycombo"), 2, 'type');
});
</script>
库.js
var selectMaker = {
create: function (table, fieldname, initialSelected, input, minimumInputLength = 3, type ='',placeholder = 'Select a element') {
if (input.data('select2')) {
input.select2("destroy");
}
input.select2({
placeholder: placeholder,
width: '100%',
minimumInputLength: minimumInputLength,
containerCssClass: type,
dropdownCssClass: type,
ajax: {
url: 'ajaxValues.php?getQuery=true&table=' + table + '&fieldname=' + fieldname + '&type=' + type,
type: 'post',
dataType: 'json',
contentType: "application/json",
delay: 250,
data: function (params) {
return {
term: params.term, // search term
page: params.page
};
},
processResults: function (data) {
return {
results: $.map(data.items, function (item) {
return {
text: item.name,
id: item.id
}
})
};
}
}
});
if (initialSelected>0) {
var $option = $('<option selected>Cargando...</option>').val(0);
input.append($option).trigger('change'); // append the option and update Select2
$.ajax({// make the request for the selected data object
type: 'GET',
url: 'ajaxValues.php?getQuery=true&table=' + table + '&fieldname=' + fieldname + '&type=' + type + '&initialSelected=' + initialSelected,
dataType: 'json'
}).then(function (data) {
// Here we should have the data object
$option.text(data.items[0].name).val(data.items[0].id); // update the text that is displayed (and maybe even the value)
$option.removeData(); // remove any caching data that might be associated
input.trigger('change'); // notify JavaScript components of possible changes
});
}
}
};
和php服务器端
<?php
if (isset($_GET['getQuery']) && isset($_GET['table']) && isset($_GET['fieldname'])) {
//parametros carga de petición
parse_str(file_get_contents("php://input"), $data);
$data = (object) $data;
if (isset($data->term)) {
$term = pSQL($data->term);
}else{
$term = '';
}
if (isset($_GET['initialSelected'])){
$id =pSQL($_GET['initialSelected']);
}else{
$id = '';
}
if ($_GET['table'] == 'mytable' && $_GET['fieldname'] == 'mycolname' && $_GET['type'] == 'mytype') {
if (empty($id)){
$where = "and name like '%" . $term . "%'";
}else{
$where = "and id= ".$id;
}
$rows = yourarrayfunctionfromsql("SELECT id, name
FROM yourtable
WHERE 1 " . $where . "
ORDER BY name ");
}
$items = array("items" => $rows);
$var = json_encode($items);
echo $var;
?>
如果您使用的是 templateSelection 和 ajax,其中一些其他答案可能无效。当您的数据对象使用 id 和文本以外的其他值时,似乎创建一个新的 option
元素并设置 value
和 text
将无法满足模板方法。
以下是对我有用的方法:
$("#selectElem").select2({
ajax: { ... },
data: [YOUR_DEFAULT_OBJECT],
templateSelection: yourCustomTemplate
}
在这里查看 jsFiddle:https://jsfiddle.net/shanabus/f8h1xnv4
在我的例子中,我不得不 processResults
输入,因为我的数据不包含必需的 id
和 text
字段。如果您需要这样做,您还需要通过相同的功能 运行 您的初始选择。像这样:
$(".js-select2").select2({
ajax: {
url: SOME_URL,
processResults: processData
},
data: processData([YOUR_INIT_OBJECT]).results,
minimumInputLength: 1,
templateSelection: myCustomTemplate
});
function processData(data) {
var mapdata = $.map(data, function (obj) {
obj.id = obj.Id;
obj.text = '[' + obj.Code + '] ' + obj.Description;
return obj;
});
return { results: mapdata };
}
function myCustomTemplate(item) {
return '<strong>' + item.Code + '</strong> - ' + item.Description;
}
对于简单的语义解决方案,我更喜欢在 HTML 中定义初始值,示例:
<select name="myfield" data-placeholder="Select an option">
<option value="initial-value" selected>Initial text</option>
</select>
因此,当我调用 $('select').select2({ ajax: {...}});
时,初始值为 initial-value
,其选项文本为 Initial text
。
我目前的Select2版本是4.0.3,但我认为它与其他版本的兼容性很好。
对我有用...
不要使用 jQuery,只使用 HTML:创建 选项值 您将显示为 selected. 如果 ID 在 select2 data 中,它将自动选择。
<select id="select2" name="mySelect2">
<option value="mySelectedValue">
Hello, I'm here!
</option>
</select>
https://github.com/select2/select2/issues/4272
只有这解决了我的问题。
即使您通过选项设置默认值,您也必须格式化具有文本属性的对象,这就是您想要在选项中显示的内容。
因此,您的格式函数必须使用 ||
来选择不为空的属性。
这是适用于我的多个 + 模板的解决方案:
(my ajax return 附加参数,“email”)
// my template
var my_template_func = function (data){
if( data.email )
var email = data.email;
else if( data.element )
var email = data.element.dataset.email;
var html = '<span><span>'+data.text+'</span> - <em>'+email+'</em></span>';
return $(html);
};
// select2 init
$('.my-select').select2({
ajax: {
url: '...',
dataType: 'json',
},
templateResult: my_template_func,
templateSelection: my_template_func,
});
然后我在 html
中设置默认选项<option value="555" data-email="test@exemple.com" selected>Bob</option>
或者我用 JS 添加选项
// add option(s)
var option = new Option('Bob', 555, true, true);
option.dataset.email = 'test@exemple.com';
$('.my-select').append(option).trigger('change');