当绑定元素名称不同时,Select2自动完成功能不起作用

问题描述:

我正在使用Select2 3.5.2。当试图绑定到labelvalue而不是idtext的数组时,Select2自动完成功能不起作用。如果有我缺少的选项,你能告诉我吗?当绑定元素名称不同时,Select2自动完成功能不起作用

jQuery(document).ready(function() { 
 
    var optionsList = [{value: 1, label: 'first'}, {value: 2, label: 'second'}, {value: 3, label: 'third'}, {value: 4, label: 'fourth'}]; 
 

 
    $("#example_select2").select2({ 
 
    data: optionsList, 
 
    dropdownAutoWidth: true, 
 
    id: 'value', 
 
    formatResult : function(item) { return item.label; }, 
 
    formatSelection: function(item) { return item.label; }       
 
    }); 
 
});
</style><!-- Ugly Hack --> 
 

 
<script src="https://code.jquery.com/jquery-2.0.3.js"></script> 
 

 
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script> 
 
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet" />
<div id="example_select2"></div>

,你所看到的问题不是因为id被改变,但是那是因为你正在使用label,而不是在你的数据对象text。 Select2将在对象的text键上默认进行匹配,因此,如果您没有设置它,它将无法找到任何内容。

您可以通过更改阵列数据以使用text或将value密钥重新映射到text密钥来解决此问题。我还建议您为您的value键(使其为id)这样做,但这不是必需的,因为Select2 3.5.2支持id选项。 Select2 4.0.0 does not.

jQuery(document).ready(function() { 
 
    var optionsList = $.map(
 
    [{value: 1, label: 'first'}, {value: 2, label: 'second'}, {value: 3, label: 'third'}, {value: 4, label: 'fourth'}], 
 
    function (obj) { 
 
    obj.id = obj.id || obj.value; 
 
    obj.text = obj.text || obj.label; 
 
    
 
    return obj; 
 
}); 
 

 
    $("#example_select2").select2({ 
 
    data: optionsList, 
 
    dropdownAutoWidth: true      
 
    }); 
 

 
});
<script src="https://code.jquery.com/jquery-2.0.3.js"></script> 
 

 
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script> 
 
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet" /> 
 

 
<input id="example_select2" type="text">

选择二也并不支持连接到<div>元素,所以我用更多的JavaScript禁用友好<input type="text" />元素交换出来。

+0

谢谢。我将把标签/值转换为文本/编号。只是试图避免做翻译,但看起来这是唯一的选择。 – mpusarla 2015-04-03 02:38:51