我试图为我的网站集成标签/自动完成功能。它通过选项文本工作。我几乎接近结果,但仍然挂着。
现在,当您尝试选择选项文本时,将出现相关文本。但是现在我也想通过选项值出现加德满都或相关选项文本搜索。
例如:当我们将搜索值A001 加德满都将会出现,并选择同A002它会出现博卡拉
$("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。
要删除的双UPSId
和Text
进入只是在表示Id
输入的期限是否匹配现有的检查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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句