Select2: add new tag dynamically using code
Asked Answered
E

3

9

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>" }
});
Evania answered 8/1, 2015 at 15:55 Comment(1)
Has anyone worked out how to do this in select2 4.0.x?Vendee
F
6

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');
Fillian answered 7/12, 2017 at 16:46 Comment(0)
E
3

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)
Evania answered 8/1, 2015 at 21:45 Comment(0)
M
3

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

Madeup answered 20/6, 2016 at 19:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.