Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>" }
});
like image 986
webber Avatar asked Jan 08 '15 15:01

webber


People also ask

How do I create a Select2 dynamically?

HTML. Create a <select class="select2_el" > element to initialize select2 on page load and create <div id="elements" > container to store <select > element on button click using jQuery AJAX.

How do you add new option if not exist in the list using Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2').

What is Select2 tag?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.

Why Select2 is not working?

Select2 does not function properly when I use it inside a Bootstrap modal. This issue occurs because Bootstrap modals tend to steal focus from other elements outside of the modal. Since by default, Select2 attaches the dropdown menu to the <body> element, it is considered "outside of the modal".


2 Answers

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');
like image 118
Roman Yakoviv Avatar answered Sep 28 '22 06:09

Roman Yakoviv


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)
like image 35
webber Avatar answered Sep 28 '22 07:09

webber