Question

I am trying to figure out how to initialize a jquery select2 item when i am in tagging mode (as i want to allow users to enter new items:

I see this example:

 $("#e12").select2({tags:["red", "green", "blue"]});

which works fine but I need to instantiate it with some entries already added.

but if i want to initialize with some existing items on page load, i tried doing something like this:

   var existingEmailAddresses= ["joe@abc.com","bill@abc.com"];

   $("#e12").select2({
            width: "600px",
            multiple: true,
            tags:["A", "B", "C"],
            initSelection: function (element, callback) {
                callback(existingEmailAddresses);
            }
        });

but that doesn't seem to be working.

How can you initialize entrying when you are using tagging mode?

Edit

I also want to see if there is any hook to validate new tags added. In my case I want to make sure they are valid email addresses.

Was it helpful?

Solution

Try

var existingEmailAddresses = ["joe@abc.com", "bill@abc.com"];

$("#e12").val(existingEmailAddresses).select2({
    width: "600px",
    multiple: true,
    tags: ["A", "B", "C"]
});

Demo: Fiddle

OTHER TIPS

In Select2 version 4.x, this got changed. Select2 is applied to a "select" tags instead of using the initSelection method, it uses a data adaptor. More info here https://select2.github.io/announcements-4.0.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top