clutchSelectBox(複数のセレクトボックスで値の絞込みを行うjs) for MovableType
複数のセレクトボックスを並べて、左から順に選んでいくと内容が絞り込まれる jsを書いてみました。今回はそれをMTで実装しました。
トップカテゴリ→サブカテゴリ→サブサブカテゴリという感じで絞り込まれる。
HTML
<div id="exhi_cat"> <ul> <li> <select name="" id="label1" size="16"> <MTTopLevelCategories> <MTSubCategories> <option value="<mt:categorylabel>"><mt:categorylabel></option> <MTSetvarBlock name="label2" append="1"> <optgroup label="<mt:categorylabel>"> <MTSubCategories> <option value="<mt:categorylabel>"><mt:categorylabel></option> <MTSetvarBlock name="label3" append="1"> <optgroup label="<mt:categorylabel>"> <MTSubCategories> <option value="<mt:categorylabel>"><mt:categorylabel></option> </MTSubCategories> </optgroup> </MTSetvarBlock> </MTSubCategories> </optgroup> </MTSetvarBlock> </MTSubCategories> </MTTopLevelCategories> </select> </li> <li> <select name="" id="label2" size="16"> <mt:var name="label2"> </select> </li> <li> <select name="" id="label3" size="16"> <mt:var name="label3"> </select> </li> </ul> </div>
Javascript
if($("#exhi_cat").length > 0){
//$.clutchSelectBox()
//複数のセレクトボックスで値の絞込みを行うjs(select>optgroup>optionなHTMLが必要)
//対象要素
var el = $("#exhi_cat");
//対象要素を複製する
var cl = el.clone();
$("select",el).attr("height","280px")
//1個目のセレクト以外を空にする
$("select",el).not(":first").empty().hide();
var len = $("select",el).length
//セレクトにイベントをセット
$("select",el).change(function(){
var index = $("select",el).index(this);
var val = $(this).val();
//この処理ではselect要素を破壊してしまうため、処理開始前に復元する
for(i=index + 1;i<len;i++){
var th = $("select",el).eq(i);
if(i == index + 1){
var tid = "#" + th.attr("id");
th.html(cl.find(tid).html());
th.show();
}
else{
th.empty();
th.hide();
}
}
var target = $("select",el).eq(index + 1);
//最後のセレクト要素で無ければ実行
if(target.length > 0){
$("optgroup",target).each(function(){
if($(this).attr("label") == val){
//IE7 fix
// http://www.kinopyo.com/blog/issue-when-using-jquery-to-manipulate-option-to-selectbox-in-ie
$(this).parent().width();
$("option",this).appendTo($(this).parent());
$(this).remove();
}
else{
$(this).remove();
//target.hide();
}
});
}
//optionが一つもないselectは隠す
if($("option", target).length == 0){
target.hide();
}
var nmArray = [];
var noArray = [];
$("select",el).each(function(){
if($(this).val()){
nmArray.push($("option:selected",this).text());
noArray.push($("option:selected",this).val());
//次のページに送るための準備
$("#categoryId").val($("option:selected",this).val());
$("#categoryIdList").val(noArray.join(","))
$("#categoryNameList").val(nmArray.join(" > "));
}
});
$("#current_cat dd").text(nmArray.join(" > "));
});
}