[英]select2 jquery plugin resets select element that have pre selected Items
I am using the Select2 tag input jQuery plugin. 我正在使用Select2标签输入jQuery插件。
I call select items and preselected items via two json formatted variables and using initSelection option to set preselected Items. 我通过两个json格式的变量并使用initSelection选项设置预选项目来调用选择项目和预选项目。
All things work perfectly, but when I choose a new item from the select box, previous items are removed from it. 一切正常,但是当我从选择框中选择一个新项目时,以前的项目将从其中删除。
How can I solve this problem? 我怎么解决这个问题?
var allTags = [{
"tag_id": 1,
"tag_title": "Laravel"
}, {
"tag_id": 3,
"tag_title": "jQuery"
}, {
"tag_id": 4,
"tag_title": "HTML"
}];
var postTags = ["tag_id": 3, "tag_title": "jQuery"
}, {
"tag_id": 4,
"tag_title": "HTML"
}
}];
var allTags = $.map(allTags, function (obj) {
obj.id = obj.id || obj.tag_id;
obj.text = obj.text || obj.tag_title;
return obj;
});
var postTag = $.map(postTags, function (obj) {
obj.id = obj.id || obj.tag_id;
obj.text = obj.text || obj.tag_title;
return obj;
});
$('[id^="meta_keywords"]').select2({
dir: "rtl",
tags: true,
initSelection: function (element, callback) {
callback(postTag);
},
data: allTags
});
This is a JsFiddle Example: 这是一个JsFiddle示例:
Multi-select when clicking on a previously selected item will deselect it. 单击先前选择的项目时,多选将取消选择它。 The initSelection code is not required, you can make them pre-selected in the data section 不需要initSelection代码,您可以在数据部分中预先选择它们
http://jsfiddle.net/ncjo6bz1/ http://jsfiddle.net/ncjo6bz1/
var allTags = [{
"tag_id": 1,
"tag_title": "Laravel",
}, {
"tag_id": 3,
"tag_title": "jQuery",
selected: true
}, {
"tag_id": 4,
"tag_title": "HTML",
selected: true
}];
var allTags = $.map(allTags, function (obj) {
obj.id = obj.id || obj.tag_id;
obj.text = obj.text || obj.tag_title;
obj.selected = obj.selected || false;
return obj;
});
$('[id^="meta_keywords"]').select2({
dir: "rtl",
tags: true,
data: allTags
});
I was unable to find a better way but if you want to hide already selected items from the drop down, some CSS can do that 我找不到更好的方法,但是如果您想从下拉菜单中隐藏已经选择的项目,则某些CSS可以做到这一点
li.select2-results__option[aria-selected='true'] {
display: none;
}
http://jsfiddle.net/ncjo6bz1/2/ http://jsfiddle.net/ncjo6bz1/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.