简体   繁体   English

从select2中的选定元素中删除一项

[英]Remove one item from selected elements in select2

I have a multiselect with many options. 我有很多选择的多重选择。 When 'everybody' is selected it removes other selected, if other are selected and the 'everybody' is selected it should remove it. 当选择“所有人”时,它将删除其他选中的对象;如果选择了其他人,并且选择了“所有人”,则应删除它。

To remove the other and keep the item 'everybody' it's ok. 删除另一个并保留“所有人”项目就可以了。 But I have problem to keep other and only remove everybody. 但是我有问题要保留其他人,而只能将所有人撤离。

For the moment I have something like : 目前,我有这样的事情:

  resetGroupSelectionWhenEverybody: function() {
    $(".group_ids").on("select2:select", function (e){
      if (e.params.data.text === 'everybody') {
        $('#scheduled_publication_groups_ids').select2({width: '50%'}).val(group_everybody_id).trigger("change");
      } else {
        if ($('[title="everybody"]').length > 0) {
          var idToRemove = 0;
          groupIdsData = $('#scheduled_publication_groups_ids').select2('data');
          groupIdsData.forEach(function(e, i) {
            if (e.text === 'everybody') {
              idToRemove = i;
            }
          });
          groupIdsData.splice(idToRemove, 1);
          $('#scheduled_publication_groups_ids').select2({'data': groupIdsData}).trigger("change");
        }
      }
    });
  },

With this code groupIdsData is tonly the selected elements I want (all expect everybody 's group). 有了这个代码groupIdsData是通联我想选择的元素(所有期待everybody的小组)。 But after I'm stuck to change the view. 但是在我坚持要改变观点之后。 select2({'data': groupIdsData}) doesn't seems to be the right choice. select2({'data': groupIdsData})似乎不是正确的选择。

Few things : 一些事情 :

  1. I don't think I'm setting the idToRemove properly 我认为我没有正确设置idToRemove
  2. What the best way to update the value of the select2 multiselect? 更新select2 multiselect值的最佳方法是什么? It seems it can be a hash 看来可能是哈希

The answer is to use select2('val') to get a array of ids, and then work with this. 答案是使用select2('val')获取ID数组,然后使用它。 Code is better using .val() not full select2 objects. 使用.val()而不是完全select2对象的代码更好。

  resetGroupSelectionWhenEverybody: function() {
    $(".group_ids").on("select2:select", function (e){
      if (e.params.data.text === 'everybody') {
        $('#scheduled_publication_groups_ids').select2({width: '50%'}).val(group_everybody_id).trigger("change");
      } else {
        if ($('[title="everybody"]').length > 0) {
          groupIds = $('#scheduled_publication_groups_ids').select2('val');
          groupToKeep = groupIds.splice( $.inArray(group_everybody_id, groupIds), 1);
          $('#scheduled_publication_groups_ids').select2({width: '50%'}).val(groupToKeep).trigger("change");
        }
      }
    });
  },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM