Jack Nicholson Jack Nicholson - 1 year ago 91
Javascript Question

SELECT2 -> Add data without replacing content

I've had a look at some other threads but nothing quite as specific. It's not really something that I would assume is hard but I'm not sure how about to do it.

Currently I'm using Select2 for a tagging system and next to it I have suggested tags which users would be able to click on and it will add to the box.

Instead, each tag is replacing the content and adding itself.

I need the adding to be appended into the box without replacing what's already in there.

Here's my code:

$(document).on('click', ".tag1", function () {
var value = $(".tag1").html();
$(document).on('click', ".tag2", function () {
var value = $(".tag2").html();

The data is being pulled through via AJAX with a span around each suggested tag.

Hope I'm clear enough.

Summary: I want to be able to click on each 'tag' and for it to be added, instead it replaces what was already in the box.


Answer Source

You should be able to do that with simple:

var test = $('#test');

    multiple: true,
    width: "300px"
var data = $(test).select2('data');
$(test).select2("data", data, true); // true means that select2 should be refreshed

Working example: http://jsfiddle.net/z96Ca/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download