webber
webber

Reputation: 1886

Select2: add new tag dynamically using code

I'm using select2 for tagging and I have it setup such that a user can add new tags as well. The issue that I'm dealing with is validating the user entry and adding the sanitized tag to selection.

To be more specific, when a user enters a space in a tag, i use formatNoMatches to display a js link to sanitize the tag and then add the tag programmatically. This code seems to run without errors but when sanitize is called all selections of the input are cleared.

Any clues where i might be going wrong?

var data=[{id:0,tag:'enhancement'},{id:1,tag:'bug'},{id:2,tag:'duplicate'},{id:3,tag:'invalid'},{id:4,tag:'wontfix'}];
function format(item) { return item.tag; }

function sanitize(a){

    $("#select").select2('val',[{
        id: -1,
        tag: a
      }]);

      console.log(a);
};

$("#select").select2({
  tags: true,
  // tokenSeparators: [",", " "],
  createSearchChoice: function(term, data) {
    return term.indexOf(' ') >= 0 ?  null :
    {
        id: term,
        tag: term
      };
  },
  multiple: true,
  data:{ results: data, text: function(item) { return item.tag; } },  formatSelection: format, formatResult: format,
  formatNoMatches: function(term) { return "\"" + term + "\" <b>Is Invalid.</b> <a onclick=\"sanitize('"+ term +"')\">Clear Invalid Charecters</a>" }
});

Upvotes: 9

Views: 16879

Answers (3)

Roman Yakoviv
Roman Yakoviv

Reputation: 1724

Only this solution works for me:

function convertObjectToSelectOptions(obj){
    var htmlTags = '';
    for (var tag in obj){
        htmlTags += '<option value="'+tag+'" selected="selected">'+obj[tag]+'</option>';
    }
    return htmlTags;
}
var tags = {'1':'dynamic tag 1', '2':'dynamic tag 2'}; //merge with old if you need
$('#my-select2').html(convertObjectToSelectOptions(tags)).trigger('change');

Upvotes: 6

Athlan
Athlan

Reputation: 6619

You can set new value (if tags you can pass array) and trigger 'change' event.

var field = $('SOME_SELECTOR');

field.val(['a1', 'a2', 'a3']) // maybe you need merge here
field.trigger('change')

About events: https://select2.github.io/options.html#events

Upvotes: 3

webber
webber

Reputation: 1886

After hacking on it some more i realized that I should be setting the new item to the "data" property and not value.

var newList = $.merge( $('#select').select2('data'), [{
        id: -1,
        tag: a
      }]);
$("#select").select2('data', newList)

Upvotes: 3

Related Questions