jQuery Select2 - select same option multiple times

2019-07-04 13:06发布

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

My tags could be:

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

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

Another issue is, now if I want to remove "commission" which is before "mortgage", it should not delete another "commission" word which is at last.

Please help me understand how to achieve this.

1条回答
叛逆
2楼-- · 2019-07-04 13:32

just use a counter and a 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 are initialized with apple/1, pear/1, ... The next time, you get apple/2, pear/2, ..., next apple/3, ... and so on.

Each time you select a fruit, you get an different id, even you choose same fruit you have previously chosen. Keeping an unique counter you increment at each select allow you to delete a fruit without side effect : its id disappeared, and will not be reused.

closeOnSelect is set to true, to increment counter at each selection (more precisely, each time you open the select box). If you set it to false, when you select a fruit, it disappears from list, and you cannot select two times same fruit, except if you close the box.

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

I hope it's that you want.

Denis

查看更多
登录 后发表回答