jQuery Select2-多次选择相同的选项 [英] jQuery Select2 - select same option multiple times

查看:424
本文介绍了jQuery Select2-多次选择相同的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的网站上创建一个页面,我想在该页面上使用此select2( http://ivaynberg .github.io/select2/)插件.我的要求是多次包含相同的单词".

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.

我的标签可能是:

  • 每月租金,每月租金,佣金,抵押,佣金
  • 同样,当用户加载页面时,我想保持用户选择页面的顺序,然后再保存.

当前,当我添加任何选项时,将从列表中将其删除.如何再次添加?

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.

推荐答案

只需使用计数器和查询功能即可提供数据:

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
}

因此,第一次单击选择框时,数据将用apple/1,pear/1,...初始化.下次,您将得到apple/2,pear/2,...,下一个苹果/3,等等.

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.

每次选择一个水果时,您都会获得一个不同的ID,即使您选择的是先前选择的相同水果.在每次选择时保持递增的唯一计数器,这样您就可以删除没有副作用的水果:其ID消失了,并且不会重复使用.

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设置为true,以在每次选择时(更精确地说,每次打开选择框)递增计数器.如果将其设置为false,则选择一个水果时,该水果将从列表中消失,并且除非关闭该框,否则不能选择两次相同的水果.

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.

验证表单时,只需删除结尾的"/xx"即可获得正确的ID.

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

我希望是你想要的.

丹尼斯

这篇关于jQuery Select2-多次选择相同的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆