2011年2月10日木曜日

検索フィルタの追加

  Redmineのソースにある、add_filter_select()関数
  (検索フィルターのリストをClickして、フィルタ名とチェックボックス表示)を、
  prototype.jsとjQuery.js の両方を使って作成してみた例


<サンプル>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
■prototype.js を使用

function addFilter() {
  var i, select, field;

  select = $('add_filter_select');
  field = select.value;
  Element.show('p_' + field);

  check_box = $('cb_' + field);
  check_box.checked = true;
  toggleFilter(field);
  select.selectedIndex = 0;

  for (i=0; i<select.options.length; i++) {
    if (select.options[i].value == field) {
      select.options[i].disabled = true;    // 選択済みの項目をdisabled
    }    
  }
}

// 選択済みフィルタのON/OFF
function toggleFilter(field) {
  var check_box = $('cb_' + field);

  if (check_box.checked) {
    Element.show('txt_' + field);
  }
  else {
    Element.hide('txt_' + field);
  }
}

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
■jQuery.js を使用

// prototype.js と共存する場合は、以下の2行を記述
jQuery.noConflict();  // jQueryの $ 参照を無効にする
var j$ = jQuery;      // jQuery を j$ に置換え

// 検索フィルタ追加
function addFilter() {
  var i, select, field;

  select = j$("#add_filter_select");

  field = select.val();
  p_field = "#p_" + field;
  j$(p_field).show();

  check_box = j$("#cb_" + field);
  check_box.attr("checked",true);
  toggleFilter(field);

  select_option = j$("#add_filter_select option:selected");
  select_option.attr("disabled",'disabled');    // 選択済みの項目をdisabled

  select.val('kokyaku_namber'); // リストの先頭へ
}

// 選択済みフィルタのON/OFF
function toggleFilter(field) {
  var check_box = j$("#cb_" + field);

  if (check_box.attr('checked')) {
    j$("#txt_" + field).show();
  } else {
    j$("#txt_" + field).hide();
  }
}