今日、私は同じ問題を抱えていました。不要なオプションを削除しないと、期待した結果が得られません。しかし問題は、後でそれらを表示したい場合に、これらのオプションを記憶する必要があることです。
私のソリューションは非常にシンプルで、すべての主要なブラウザーで動作します。
function filterList(oList, rxSearch)
{
// Create backup of the old option list (only once)
if(typeof(oList.tagOptions) === "undefined")
{
// Save current options
oList.tagOptions = [ ]; // Generate a dynamic property for this DOM object
for(var i = 0; i < oList.options.length; ++i)
oList.tagOptions.push(oList.options[i]);
}
// Clear the current option list
while(oList.options.length)
oList.options.remove(0);
// Add only those options which match the regular expression
for(var i = 0; i < oList.tagOptions.length; ++i)
{
if(rxSearch.test(oList.tagOptions[i].text))
oList.options.add(oList.tagOptions[i]);
}
}
秘訣は、オプション要素が最初の実行時に動的に作成された tagOptions プロパティにコピーされることです。これらの削除されたオプション DOM 要素への (tagOptions 内の) 参照がまだ存在するため、それらは解放されません。さらに、そのためのグローバル変数は必要ありません。その後、表示されているオプション (oList.options) はクリアされ、検索語に一致するオプションのみが追加されます。
次の HTML コードを使用します。
<select id="myList" size="10">
<option>apple</option>
<option>advocado</option>
<option>banana</option>
<option>coconut</option>
</select>
次のように呼び出します。
filterList(document.getElementById("myList"), /^a/i); // Display only those elements, which start with an a
alert("Display all with a");
filterList(document.getElementById("myList"), /^b/i); // Display only those elements, which start with an b
alert("Display all with b");
filterList(document.getElementById("myList"), /^/i); // Display only those elements, which start with an c
alert("Display all");
Firefox、Internet Explorer 11、Chrome、および Opera でこれをテストしました。それは私の目的のためにうまくいきます。
function filterList(oList, rxSearch)
{
// Create backup of the old option list (only once)
if(typeof(oList.tagOptions) === "undefined")
{
// Save current options
oList.tagOptions = [ ]; // Generate a dynamic property for this DOM object
for(var i = 0; i < oList.options.length; ++i)
oList.tagOptions.push(oList.options[i]);
}
// Clear the current option list
while(oList.options.length)
oList.options.remove(0);
// Add only those options which match the regular expression
for(var i = 0; i < oList.tagOptions.length; ++i)
{
if(rxSearch.test(oList.tagOptions[i].text))
oList.options.add(oList.tagOptions[i]);
}
}
filterList(document.getElementById("myList"), /^a/i); // Display only those elements, which start with an a
alert("Display all with a");
filterList(document.getElementById("myList"), /^b/i); // Display only those elements, which start with an b
alert("Display all with b");
filterList(document.getElementById("myList"), /^/i); // Display only those elements, which start with an c
alert("Display all");
<select id="myList" size="10">
<option>apple</option>
<option>advocado</option>
<option>banana</option>
<option>coconut</option>
</select>