2013-02-20 72 views
4

http://jsfiddle.net/tXFbk/2/选择二多选重复值

HTML:

<div class="control-group"> 
    <label for="some_id" class="control-label">Some ID</label> 
    <div class="controls"> 
     <input type="text" id="some_id" name="some_id" class="span4"/> 
    </div> 
</div> 

JS:

$(function() { 
    $('#some_id').select2({ 
     allowClear: true, 
     placeholder: 'Some ID', 
     minimumInputLength: 2, 
     multiple: true, 
     data: [ 
      {id: 1, text: 'some text'}, 
      {id: 2, text: 'some other text'}, 
      {id: 3, text: 'some more text'} 
     ] 
    }); 
    $('#some_id').select2('data', [ 
     {'id':1,'text':'some text'} 
    ]); 

    console.log($('#some_id').select2('val')); 
}); 

在第一负载它重复值和清除值之后,在没有明确它从输入。此外,如果您添加一个项目(例如“更多文本”),然后将其删除,它不会从输入值中清除它。有没有办法让它停止重复值? 还有一件事 - 如何禁用添加已添加的项目?

+0

你有没有找到一个答案? – MCB 2015-08-28 17:53:45

回答

0

您需要触发select2的更改事件以反映更改。

$("#dropdownId").val("yourValues").trigger("change"); 

设定值后,您需要手动触发的触发值,以反映您的下拉列表

1

检查所做的最新变化如下在选择事件,并且在设置是否新款财产createSearchChoice

让我知道如果它解决您的问题

$('#some_id').select2({ 
      tags: true, 
      tokenSeparators: [","], 
      createSearchChoice: function (term, data) { 
       if (term.trim().length > 0) { 
        if ($(data).filter(function() { 
         return this.text.toLowerCase().localeCompare(term.toLowerCase()) === 0; 
        }).length === 0) { 
         return { 
          id: term, 
          text: term, 
          isNew: true // this is necessary to check if the item is newly added or not 
         }; 
        } 
       } 
      }, 
      multiple: true, 
      minimumInputLength: 1, 
      allowClear: true, 
      data: [ 
     {id: 1, text: 'some text'}, 
     {id: 2, text: 'some other text'}, 
     {id: 3, text: 'some more text'} 
    ], 
     }).on("select2-selecting", function (e) { 
      var tagId = ''; 
      if (e.choice.isNew) { 
       self.AddTagToDatabase(e.choice.text); 
      } else { 
       var isValidTag = true; 
       $(config.element[0] + ' ul li').find('div').each(function (index, item) { 
        if ($(item).html().toLowerCase().trim() == e.choice.text.toLowerCase().trim()) { 
         isValidTag = false; 
         e.choice.text = ''; 
         return; 
        } 
       }); 
      } 
     }) 
1

Select2 4.0.0支持重复标签。

Jsfiddle Demo link

$eventSelect.on("select2:select", function (e) { 
    log("select2:select", e); 
    $eventSelect.append('<option value="'+e.params.data.text+'">' +e.params.data.text + '</option>'); 
}); 

$eventSelect.on("select2:unselect", function (e) { 
    log("select2:unselect", e); 
    e.params.data.element.remove(); 
}); 

function formatResultData (data) { 
    if (!data.id) return data.text; 
    if (data.element.selected) return 
    return data.text; 
}; 

此基础上选择2事件和github issues

图片: enter image description here

+0

与您的示例有重新排序问题。选择“红色,红色,绿色”,获得“红色,绿色,红色” – 2018-02-16 08:56:46