LoginSignup
14
14

More than 5 years have passed since last update.

Datatablesの使い方

Last updated at Posted at 2015-01-04

Datatablesはテーブルをいい感じに表示してくれるjqueryプラグイン
ココにデモが、ココにソースがある。

とりあえず表示だけ

datatables.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
  <!-- Datatables -->
  <link rel="stylesheet" href="./lib/DataTables/media/css/jquery.dataTables.min.css" >
  <script src="./lib/DataTables/media/js/jquery.dataTables.min.js"></script>
  <script>
    /* javascript */
  </script>
</head>
<body>
  <table id="datatables">
  </table>
</body>
</html>
javascript
var Ggrd_Table = null;
$(function(){
  Ggrd_Table = $('#datatables').DataTable({
    "columns": [
      { "title": "aaa" },
      { "title": "bbb" },
      { "title": "ccc" },
    ]
  });
});

これでテーブルのヘッダ付きの枠組みだけ表示される。
内容を追加するには以下の方法で要素を追加していく。

テーブルの行追加、削除

追加

Ggrd_Table.row.add([
  "aaa",
  "bbb",
  "ccc"
]).draw();

削除

Ggrd_Table.row(idx).remove().draw();
// idxはrow index number (0起算)

選択されている行を削除する

// 「クリックした行の色を変化させる」をやった上で、
Ggrd_Table.rows( '.selected' ).remove().draw();

クリックした行の色を変化させる(single select)

$('#datatables tbody').on( 'click', 'tr', function () {
  Ggrd_Table.$('tr.selected').removeClass('selected');
  $(this).addClass('selected');
});

14
14
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
14
14