我的服务器回调已经预先过滤了数据,我希望 Tom Select 显示给定查询返回的所有结果。我尝试通过设置
searchField: []
来实现此目的。但是,这也会保留之前输入的查询的结果。
示例:
哪种选项组合允许我导致这种行为?
这是一个最小的可重现示例:
function search(q, callback) {
if (q === "Zürich" || q === "Zuerich") {
callback([{
'text': 'Zürich',
'value': 1
},
{
'text': 'Zuerich',
'value': 2
}
]);
} else if (q === "St. Gallen" || q === "St Gallen") {
callback([{
'text': 'St. Gallen',
'value': 3
},
{
'text': 'St Gallen',
'value': 4
}
]);
} else {
callback();
}
}
var settings = {
load: (q, callback) => this.search(q, callback),
searchField: []
};
new TomSelect('#tom-select-it', settings);
<meta charset="UTF-8">
<input id="tom-select-it" />
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/tom-select.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/tom-select.complete.min.js"></script>
这并非小事。
我尝试了DOCS
我添加了变音符号以及退格键的键盘处理程序
let inputElement;
const handleKeyUp = (event) => {
const query = inputElement.value.trim();
// Clear options for each keyup to refresh results
if (query === "") {
// If the input is empty, close the dropdown
tS.close();
tS.load(query, callback => callback([])); // Pass an empty result set
}
};
const normalizeText = (text) => text.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
const search = (q, callback) => {
q = normalizeText(q); // Normalize query input
console.log('?', q)
// Filter results by normalized text
const filteredResults = results.filter(item =>
normalizeText(item.text).includes(q)
);
callback(filteredResults);
}
const settings = {
diacritics: true,
loadThrottle: 300,
type: () => console.log("q", q),
load: function(q, callback) {
inputElement = document.getElementById('tom-select-it-ts-control'); // add a keyup event handler for backspace
inputElement.addEventListener('keyup', handleKeyUp);
if (q.trim() === "") { // Check if the query is empty
this.clearOptions(); // Clear options
this.refreshItems();
callback([]); // Stop further processing
return;
}
search(q, callback); // Call the search function with query if input is not empty
},
searchField: ['text']
};
let tS = new TomSelect('#tom-select-it', settings);
<meta charset="UTF-8">
<input id="tom-select-it" />
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/tom-select.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/tom-select.complete.min.js"></script>
<script>
const results = [{
'text': 'Zürich',
'value': 1
},
{
'text': 'Zuerich',
'value': 2
},
{
'text': 'St. Gallen',
'value': 3
},
{
'text': 'St Gallen',
'value': 4
}
];
</script>