我已尝试为我的站点集成标签/自动完成功能。它通过选项文本工作。我快接近结果了,但仍然悬而未决。
现在,当您尝试选择选项文本时,会出现相关文本。但现在我也想通过选项值搜索 kathmandu 或相关选项文本。
例如: 当我们搜索值时 a001 kathmandu 将出现并选择与 a002 相同,它将出现 pokhara
$("select").select2({
tags: "true",
placeholder: "Select an option",
allowClear: true,
width: '100%',
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
value: true // add additional parameters
}
}
});
.select2-container {
max-width: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select class="custom-select" multiple="multiple">
<option value="a001">Kathmandu</option>
<option value="a002">Pokhara</option>
<option value="a003">Lalitpur</option>
</select>
我认为通过值搜索后我很接近并单击它,它将显示带有 id 的相关选项。但我只想要像 pokhara kathmandu 这样的选项文本,而不是选择区域的 ID。
最佳答案
要删除在仅输入 Id
时显示的 Id
和 Text
的重复,请检查输入的术语是否与现有的匹配Id
,如果确实返回匹配选项的 Text
:
options = [];
// create an array of select options for a lookup
$('.custom-select option').each(function(idx) {
options.push({id: $(this).val(), text: $(this).text()});
});
$("select").select2({
tags: "true",
placeholder: "Select an option",
allowClear: true,
width: '100%',
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
// check whether the term matches an id
var search = $.grep(options, function( n, i ) {
return ( n.id === term || n.text === term); // check against id and text
});
// if a match is found replace the term with the options' text
if (search.length)
term = search[0].text;
else
return null; // didn't match id or text value so don't add it to selection
return {
id: term,
text: term,
value: true // add additional parameters
}
}
});
$('select').on('select2:select', function (evt) {
//console.log(evt);
//return false;
});
.select2-container {
max-width: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select class="custom-select" multiple="multiple">
<option value="a001">Kathmandu</option>
<option value="a002">Pokhara</option>
<option value="a003">Lalitpur</option>
</select>
关于javascript - Select2 按选项值自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42967268/