Search code examples
jquerytagsjquery-select2tagging

How do you initialize jquery select2 items when you are in "tagging" mode?


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= ["[email protected]","[email protected]"];

   $("#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.


Solution

  • Try

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

    Demo: Fiddle