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

查看:27
本文介绍了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.

我的标签可能是:

  • Monthly_Rent、Monthly_Rent、佣金、抵押、佣金
  • 此外,当用户加载页面时,我想保持用户在保存之前选择它的顺序.

目前,当我添加任何选项时,它会从列表中删除.如何重新添加?

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, ..., nextapple/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天全站免登陆