Select2: dynamically add a new tag using code

I use select2 for tags, and I have this setting so that the user can add new tags. The problem I am facing is checking the user input and adding a sanitized tag to the selection.

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

Any clues where can I go 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>" } }); 
+7
javascript jquery-select2
source share
3 answers

After hacking a little more, I realized that I should set a new element in the data property, not the value.

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

You can set a new value (if you can pass tags in an array) and trigger the "change" event.

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

About the events: https://select2.imtqy.com/options.html#events

+2
source share

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'); 
+1
source share

All Articles