我正在尝试将数据属性设置到select2选项中,但没有成功,目前我有以下JS代码
_properties.$localElement.select2({
ajax: {
url: "url",
type: "POST",
dataType: 'json',
delay: 250,
data: function (params) {
return {
name: params.term, // search term
type: 1
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
source: item.source,
id: item.id
}
})
};
},
cache: true
},
//define min input length
minimumInputLength: 3,
});
并且我想为所选的选项值设置一个数据源。
发布于 2016-09-15 17:04:14
我找到了解决方案,看起来resultTemplate没有格式化“可视”选择的选项,需要使用templateSelection选项:
templateSelection: function(container) {
$(container.element).attr("data-source", container.source);
return container.text;
}
发布于 2020-06-23 10:20:52
实际上,您可以使用您已经使用过的语法。"source-attribute“只需要通过特定select2-.data.source的data()选项来访问。
因此,保留您的processResults函数:
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
source: item.source,
id: item.id
}
})
};
},
如果你想检索所选选项的源代码,你可以这样做:
var selectedSelect2OptionSource = $("#idOfTheSelect2 :selected").data().data.source;
实际上,您可以在processResults函数中设置任何变量,然后通过data().data.variableName选择它!
发布于 2020-08-31 00:38:03
我解决了这个问题。
$('select').on('select2:select', function (e) {
var data = e.params.data;
$("select option[value=" + data.id + "]").data('source', data.source);
$("select").trigger('change');
});
https://stackoverflow.com/questions/39515230
复制相似问题