ちょっと人に頼まれて実現してみた。
jqGrid関連の情報は、割りと古いものが多かったりするので、最新の v4.8.2 で実現するのに、ちょっと戸惑った。
実現イメージは、こんな感じ。
各行の左端にボタンを置いて、それを押した時の振る舞いをハンドリングすること。
まずは、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>
</head>
<body>
<table id="sample"></table>
</body>
</html>
続いてJavaScript。
ドキュメントを見ると、列の設定でedittypeにbuttonを指定すればボタンを置けそうなんだけど、結局実現できなくて、formatterを自分で作れば実現できた。
まずは、列の設定で自作のformatterを指定する。
{name: "buttonSel", index: "buttonSel", formatter: buttonFormat, search: false},
続いて、カスタムformatterを実装する。
と言っても、単に出力したいHTMLを文字列で返すだけ。
押したボタンの行を知りたいので、data-rowidに行番号をセットするようにしている。
function buttonFormat(cellvalue, options, rowObject) {
return '<button type="button" class="selectButton" data-rowid="' + options.rowId + '">選択</button>';
}
ボタンを押した時のイベントはこんな感じ。
$(this).data('rowid')
で選択されたボタンの行数が取れる
$('.selectButton').on('click', function(event) {
console.log('button click : ' + $(this).data('rowid'));
});
JavaScript全体は、こんな感じ。
$(function() {
var displayData = [
{No: 1, col1: "1", col2: "りんご", col3:5},
{No: 2, col1: "2", col2: "バナナ", col3:10},
{No: 3, col1: "3", col2: "バナナ", col3:2},
{No: 4, col1: "4", col2: "りんご", col3:14},
{No: 5, col1: "5", col2: "ミカン", col3:5},
];
//列の設定
var colModelSettings= [
// ボタンにする行のformatterを自作の 'buttonFormat' にマッピング
{name: "buttonSel", index: "buttonSel", formatter: buttonFormat, search: false},
{name: "col1", index: "col1", search: false},
{name: "col2", index: "col2"},
{name: "col3", index: "col3"},
];
//列の表示名
var colNames = ["", "ID", "果物の種類", "在庫"];
//テーブルの作成
$("#sample").jqGrid({
data:displayData,
datatype : "local",
colNames : colNames,
colModel : colModelSettings,
rowNum : 100,
rowList : [1, 10, 20],
caption : "果物在庫表",
height : 200,
width : 600,
pager : 'pager',
regional : 'ja',
viewrecords: true,
cellEdit:true
});
$('.selectButton').on('click', function(event) {
// ボタン押下時の振る舞いはここへ
// $(this).data('rowid') で選択されたボタンの行数が取れる
console.log('button click : ' + $(this).data('rowid'));
});
// ボタン生成用関数
function buttonFormat(cellvalue, options, rowObject) {
return '<button type="button" class="selectButton" data-rowid="' + options.rowId + '">選択</button>';
}
});