dr3x
dr3x

Reputation: 987

Select2 tags - dynamically adding to preselected

I'm using select2 tagging which I set up like this:

  $("#el1").select2({
    tags: tags,
    tokenSeparators: [",", " "]
  });

And then I'm hooking the element onchange event so that if a tag is added or deleted I make an ajax call to update the database (e.added/.deleted).

How do I add tags to the preselected list dynamically without destroying/recreating the select2 object?

Upvotes: 0

Views: 2174

Answers (2)

macieklag
macieklag

Reputation: 11

It's my solution for initial selected values

$( function() {
    var selectedValue = ['1', '2', 'New tag'];

    for ( var i = 0; i < selectedValue.length; i++ ) {
        if ( $( 'form :input[name="multiple-select[]"] option[value="' + selectedValue[i] + '"]' ).length < 1 ) {
            $( 'form :input[name="multiple-select[]"]' ).append(
                '<option value="' + selectedValue[i] + '" data-select2-tag="true">' + selectedValue[i] + '</option>'
            );
        }
    }

    $( 'form :input[name="multiple-select[]"]' )
        .select2( {
            tags: true
        } )
        .val( selectedValue )
        .trigger( "change" )
    ;
} );

Upvotes: 0

Paullo
Paullo

Reputation: 2127

If you want to select/add a new tag dynamically; you can use this

$("#el1").val("New").trigger("change");

But if what you want is to change/update tags dataSource dynamically. It is a pity you can't do that without destroy and re-creating the select2

Upvotes: 1

Related Questions