[英]How can I auto filter a HTML selectlist?
我有一個HTML選擇列表,其中包含很多(1000多個)名稱。 我有一個javascript,如果有人開始輸入,它將選擇第一個匹配的名稱。 此匹配項顯示在項目的開頭:
var optionsLength = dropdownlist.options.length;
for (var n=0; n < optionsLength; n++)
{
var optionText = dropdownlist.options[n].text;
if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)
{
dropdownlist.selectedIndex = n;
return false;
}
}
客戶想要一個建議或自動過濾器:鍵入名稱的一部分應“查找”包含該部分的所有名稱。 我已經看到了一些“ Google建議”之類的選項,大多數使用Ajax,但是我想要一個純JavaScript選項,因為選擇列表已經加載了。 指針有人嗎?
更改
if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)
至
if (optionText.indexOf(dropdownlist.keypressBuffer) > 0)
要在optionText
任意位置找到dropdownlist.keypressBuffer
。
我將設置一個緩存來保存select
內的options
。 而且,除了清除options
中的select
,我將清除select
,然后使用匹配的options
重新填充它。
偽代碼嘉豪:
onLoad:
set cache
onKeyPress:
clear select-element
find option-elements in cache
put found option-elements into select-element
這是我寫的一些POC,對另一個select
selects
的內容進行過濾-實際上將一堆選擇鏈接在一起。
也許它可以給您一些想法:
function selectFilter(_maps)
{
var map = {};
var i = _maps.length + 1; while (i -= 1)
{
map = _maps[i - 1];
(function (_selectOne, _selectTwo, _property)
{
var select = document.getElementById(_selectTwo);
var options = select.options;
var option = {};
var cache = [];
var output = [];
var i = options.length + 1; while (i -= 1)
{
option = options[i - 1];
cache.push({
text: option.text,
value: option.value,
property: option.getAttribute(_property)
});
}
document.getElementById(_selectOne).onchange = function ()
{
var selectedProperty = this
.options[this.selectedIndex]
.getAttribute(_property);
var cacheEntry = {};
var cacheEntryProperty = undefined;
output = [];
var i = cache.length + 1; while (i -= 1)
{
cacheEntry = cache[i - 1];
cacheEntryProperty = cacheEntry.property;
if (cacheEntryProperty === selectedProperty)
{
output.push("<option value=" + cacheEntry.value + " "
_property + "=" + cacheEntryProperty + ">" +
cacheEntry.text + "</option>");
}
}
select.innerHTML = output.join();
};
}(map.selectOne, map.selectTwo, map.property));
}
}
$(function ()
{
selectFilter([
{selectOne: "select1", selectTwo: "select2", property: "entityid"},
{selectOne: "select2", selectTwo: "select3", property: "value"}
]);
});
YUI庫具有用於此類功能的庫,稱為AutoComplete 。
AutoComplete的數據源可以是本地javascript對象,如果您改變主意,則可以輕松切換到Ajax。
YUI組件可以通過相當多的功能進行自定義。
編輯:我不確定是否可以讓它與問題所要求的選擇框一起使用。 可能是可能的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.