0
votes

I am using the Select2 tag input jQuery plugin.

I call select items and preselected items via two json formatted variables and using initSelection option to set preselected Items.

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:

See On JsFiddle

1
It looks like what is happening is you have "HTML", "jQuery" pre-selected, but the drop down list is not reflecting that. Clicking on an already selected item, it gets toggled on/off. Clicking "Laravel" will add it to the selected options and not remove anything elsesmcd

1 Answers

1
votes

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

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

li.select2-results__option[aria-selected='true'] {
    display: none;
}

http://jsfiddle.net/ncjo6bz1/2/