简体   繁体   中英

Select2 Tags: Dynamicly add tag to input

I am looking for a solution to add a tag to the input tag field.

I know it is possible to have preloaded tags, but I have found no way to add a tag to the input. Ie using a specific function, I could append a selection (with ID and TEXT).

I have searched quite a bit, but maybe I'm in a dead loop. Any suggestions?

This is how I initialize:

    $('.select2Input').select2({
        tags: {
            0: {
                id: 'the id',
                text: 'the text'
            }
        },
        multiple: true,
        minimumInputLength: 2
    });

As i mentioned in this related question select2 destroy and recreate , the trick lies in destroying and recreating the select2 when you need to change the initialization options. i suspect that this is what you need to do in your case as well.

the basic syntax is

$('#categoryid').select2("destroy");
createmycategoryidselect();

function createmycategoryidselect() {
   // standard options
   $opts = { ... }
   // gather the current set of tag values and stick them in this new instance.
   $opts.tags = { ... new tags ... }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM