selectタグの option を他の入力フィールドで入力したキーワードフィルタで動的に絞り込む要求がありました。
サーバと通信をして select タグを書きなおすということをしたくなかったので、jQuery だけで検索するように書きました。
(1文字キーが押される度にサーバーに問い合わせたくなかったからです。)
汎用性の為に、メソッド化しました。
var pulldownFilter = function(filter, selecter){
var optionArray = new Array();
$(selecter).children().each(function(){
optionArray.push( { value:$(this).prop("value"), body:$(this).html() });
});
$(filter).keyup(function(){
var s = $(this).val();
$(selecter).empty();
if (s==""){
$(optionArray).each(function(i, o){
$(selecter).append( $('<option>').val(o.value).text(o.body) );
});
}else{
optionArray.filter(function(o, i){
if (o.body.match(s)){
$(selecter).append( $('<option>').val(o.value).text(o.body) );
}
});
}
});
};
以下のような HTMLがあったら、
<input type="text" id="filter" placeholder="キーワードフィルタ">
<select id="selectItems" name="selectItems">
jQurey 実行として、
$(function(){
pulldownFilter('#filter', '#selectItems');
});
と書きます。。