LoginSignup
1
5

More than 5 years have passed since last update.

jqGridで列に対する検索フィルターを動的に作成した選択肢のセレクトボックスにする

Posted at

これも人に頼まれて実現したもの。
jqGridの検索フィルターは、デフォルトでテキストボックスとセレクトボックスをセットできる。

ただ、このセレクトボックスの項目は、静的に項目を並べた例が多くて、列の値を選択肢として動的に作った例がなかったので自作。

実現イメージは、こんな感じ。

スクリーンショット 2015-07-16 21.20.00.png

まずは、HTML。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
    <title>jqGridSample</title>
    <link type="text/css" media="screen" href="css/jquery-ui.min.css" rel="stylesheet" />
    <link type="text/css" media="screen" href="css/ui.jqgrid.css" rel="stylesheet" />
    <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="js/jquery.jqGrid.src.js"></script>
    <script type="text/javascript" src="js/i18n/grid.locale-ja.js"></script>
    <script type="text/javascript" src="js/underscore-min.js"></script>
</head>
<body>
  <table id="sample"></table>
</body>
</html>

続いてJavaScript。

まずは、列の設定で検索オプションとともに、選択肢を作成する関数(createSearchChoices)を呼び出す。
stypeをselectにして、searchoptionsで選択肢を指定。

{name: "col2", index: "col2",
 stype: 'select', searchoptions: { value: createSearchChoices(displayData, "col2"), sopt: ['cn'] }}

検索条件は、以下のような関数で生成した。
列の値をマージするのが面倒で、underscore.jsを利用。

function createSearchChoices(targetData, targetAttrName) {
  var colSelections = { "": "" };
  var cols = _.uniq(_.map(targetData, function(it) {return it[targetAttrName];}));
  cols.forEach(function(it) {colSelections[it] = it;});

  return colSelections;
}
1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5