JQuery Select2 - selecting the same option multiple times

I am trying to make a page on my website where I want to use this select2 ( http://ivaynberg.github.io/select2/ ). My requirement is to include the same "words" multiple times.

My tags can be:

  • Monthly_Rent, Monthly_Rent, commission, mortgage, commission.
  • Also, when the user loads the page, I want to keep the order as the user selected it before saving.

Currently, when I add any option, it is removed from the list. How can I add it again?

Another problem: now, if I want to remove the "commission" that is before the "mortgage", it should not remove another "commission" word, which is finally.

Please help me understand how to achieve this.

+3


source to share


1 answer


just use counter and query function to provide data:

var fruits = ['apple', 'pear', 'orange', 'strawberry']
var counter = 0

$("#yourinput").select2({
    query: function(query) {
        var data = { results: []};
        for (var i = 0; i < fruits.length; i++) {
            data.results.push({"id": fruits[i] + "/" + counter, "text": fuits[i]});
        }
        counter += 1;
        query.callback(data);
    },
    formatSelection: function(item) {
        return item.text; // display apple, pear, ...
    },
    formatResult: function(item) {
        return item.id; // display apple/1, pear/2, ... Return item.text to see apple, pear, ...
    },
    multiple: true,
    closeOnSelect: true
}

      

So the first time you click on your select box, the data is initialized with apple / 1, pear / 1, ... Next time you get apple / 2, pear / 2, ..., next apple / 3, ... and etc.

Every time you choose a fruit, you get a different ID, even you choose the same fruit that you chose earlier. By keeping a unique counter that you increment with each selection, you can remove the fruit with no side effect: its ID is gone and won't be reused.



closeOnSelect is true to increment the counter on every selection (more precisely, every time you open a select box). If you set it to false when you select a fruit, it disappears from the list, and you cannot select the same fruit twice, except when you close the window.

When you validate your form, just remove the "/ xx" trailing to get the correct ID.

Hope you like it.

Denis

+1


source







All Articles