问题
I Would like display tags from a select2 form into another DIV. I tried the solution proposed by TJ Nicolaides https://stackoverflow.com/a/34140018/3030970 but it does not work on jQuery > 3 when you remove a tag, then add it again, you can not remove it any more
$(".js-example-tags").select2({
tags: true
}).on('change', function() {
var $selected = $(this).find('option:selected');
var $container = $(this).siblings('.js-example-tags-container');
var $list = $('<ul>');
$selected.each(function(k, v) {
var $li = $('<li class="tag-selected"><a class="destroy-tag-selected">×</a>' + $(v).text() + '</li>');
$li.children('a.destroy-tag-selected')
.off('click.select2-copy')
.on('click.select2-copy', function(e) {
var $opt = $(this).data('select2-opt');
$opt.attr('selected', false);
$opt.parents('select').trigger('change');
}).data('select2-opt', $(v));
$list.append($li);
});
$container.html('').append($list);
}).trigger('change');
The fiddle proposed by TJ Nicolaides : http://jsfiddle.net/tjnicolaides/ybneqdqa/
Is the problem related to the data() method?
Thx for your help :)
回答1:
I finally found a solution, it was not relative to the data()
method but to the attr()
method used to set the selected value to false.
I simply replace attr()
by prop()
method, more adapted to this context.
$(".js-example-tags").select2({
tags: true
}).on('change', function() {
var $selected = $(this).find('option:selected');
var $container = $(this).siblings('.js-example-tags-container');
var $list = $('<ul>');
$selected.each(function(k, v) {
var $li = $('<li class="tag-selected"><a class="destroy-tag-selected">×</a>' + $(v).text() + '</li>');
$li.children('a.destroy-tag-selected')
.off('click.select2-copy')
.on('click.select2-copy', function(e) {
var $opt = $(this).data('select2-opt');
$opt.prop('selected', false); // <-- Main difference
$opt.parents('select').trigger('change');
}).data('select2-opt', $(v));
$list.append($li);
});
$container.html('').append($list);
}).trigger('change');
来源:https://stackoverflow.com/questions/47020807/select2-display-tags-into-another-div