Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new tags in a Select2 tag textarea

I have an input (textarea) that has Select2's tags applied to it. So when a user types in the name of an item that exists in my data base, it shows a list of matching items and the user can select one and a tag is created.

Here is my code so far for basic tag functionality:

$('#usualSuppliers').select2({
        placeholder: "Usual suppliers...",
        minimumInputLength: 1,
        multiple: true,
        id: function(e) {
            return e.id + ":" + e.name;
        },
        ajax: {
            url: ROOT + 'Ajax',
            dataType: 'json',
            type: 'POST',
            data: function(term, page) {

                return {
                    call: 'Record->supplierHelper',
                    q: term,
                    page_limit: 10
                };
            },
            results: function(data, page) {
                return {
                    results: data.suppliers
                };
            }
        },
        formatResult: formatResult,
        formatSelection: formatSelection,
        initSelection: function(element, callback) {
            var data = [];
            $(element.val().split(",")).each(function(i) {
                var item = this.split(':');
                data.push({
                    id: item[0],
                    title: item[1]
                });
            });
            //$(element).val('');
            callback(data);
        }
    });

Is there a way for a new tag to be created if the text typed does not exist? Initially I thought this could some how be done by delimiting with spaces, but some items (supplier names) will have spaces in them, so that won't work.

I think when no matches are found the user needs to somehow "create" the tag by pressing a button that could appear in the drop down box, but I have no idea how to do this.

How can I allow users to create new tags that may have spaces in them and still be able to carry on adding more tags, existing or otherwise?

like image 412
imperium2335 Avatar asked Nov 11 '13 09:11

imperium2335


1 Answers

Yes you can do it. There is a example in the documentation. Look at http://ivaynberg.github.io/select2/#events

$("#e11_2").select2({
  createSearchChoice: function(term, data) { 

   if ($(data).filter( function() { return this.text.localeCompare(term)===0;   
         }).length===0) {
     return {id:term, text:term};
   } 

  },
  multiple: true,
  data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});

You have to create a function like createSearchChoice, that returns a object with 'id' and 'text'. In other case, if you return undefined the option not will be created.

like image 94
pipo02mix Avatar answered Oct 04 '22 22:10

pipo02mix